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 moment it says "select a file" every time.
<select name="image" type="text" class="box" id="image" value="<?=$image;?>">
<option value='empty'>Select a file</option>
<?php
$dirname = "images/";
$images = scandir($dirname);
// This is how you sort an array, see http://php.net/sort
natsort($images);
// There's no need to use a directory handler, just loop through your $images array.
foreach ($images as $file) {
if (substr($file, -4) == ".gif") {
print "<option value='$file'>$file</option>\n"; }
}
?>
</select>
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";
}
}
?>
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";
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.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.