Search code examples
javascriptphpdropdown

Listing files in a dropdown menu linking to these


I want a dropdown menu to appear which lists all PDF files i have in a directory and making each entry clickable, linking to the specific file.

I have already tried a lot and the Dropdown menu with the PDFs listed actually shows up, but when i tried adding a Button next to it to open a new page with the PDF file, but when clicking it, nothing would happen at all

<select name="PdfFile" id="target" class="pdfliste">
<option value="">- Wähle Datei -
<?php 
$dirPath = dir('beispiel');
$imgArray = array();
    while (($file = $dirPath->read()) !== false)
{
   $imgArray[ ] = trim($file);
}
$dirPath->close();
sort($imgArray);
$c = count($imgArray);
for($i=0; $i<$c; $i++)
{
    echo "<option value=\"" . $imgArray[$i] . "\">" . $imgArray[$i] . "\n";
}

?>
</select>
    <input type="button" class="button-spec" value="Visit Link!"
         onclick="goToNewPage(document.dropdown.PdfFile)">';

JAVASCRIPT

function goToNewPage() {
  if(document.getElementById('target').value) {
    window.location.href = document.getElementById('target').value;
  }
}

Solution

  • I found two things now:

    1. Your HTML Option tag weren't closed

    echo "<option value=\"" . $imgArray[$i] . "\">" . $imgArray[$i] . "</option>\n";

    1. Javascript at the button onClick was wrong

    <input type="button" class="button-spec" value="Visit Link!" onclick="goToNewPage()">

    Now you can choose one file, click on the button and get redirected.

    For more information here now: First the option tags weren't closed (maybe automatic by browser), but so you had file1, file2, etc. in one HTML tag. (makes no difference, as I tested it out without the closed option tags)

    If you want to use the onclick with the files name you will need to correct your function so it gets the input, lemme give you the example for that: <input type="button" class="button-spec" value="Visit Link!" onclick="goToNewPage(document.getElementById('target').value)">

    function goToNewPage(newPageUrl){window.location.href = newPageUrl;}

    Hope this helps :)