Skip to content Skip to sidebar Skip to footer

Selected Entry In A Drop Down Select HTML Form Element

This drop down list, displaying all the files from a folder, one of which will be selected for use. Is there a way to show which file is selected when you load the page? At the mom

Solution 1:

I get the feeling SO is writing your application for you bit by bit...

anyway,

<?php
foreach ($images as $file) {
    if (substr($file, -4) == ".gif") {
        print "<option value='$file'"
            . ($file == $image ? " selected" : "")
            . ">$file</option>\n";
    }
}
?>


Solution 2:

use the "selected" tag on your option for the file that is selected

first check to see which file is selected from the post or get (it's unclear what action the form is taking from your post.. assuming get)

use the ternary operator in your loop:

$selected = $_GET['image'] == $file ? "selected" : "";

print "<option $selected value='$file'>$file</option>\n";

Solution 3:

And similarly to Zak's and NickF's answers, you can use

selected="selected"

in your option tag if you like to go for XHTML.

(On a side-note, my new reputation does not allow me to add comments to answers yet.)


Post a Comment for "Selected Entry In A Drop Down Select HTML Form Element"