Selected Entry in a Drop Down Select HTML Form Element

一个人想着一个人 提交于 2019-12-13 02:51:40

问题


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>

回答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";
    }
}
?>




回答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";



回答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.)



来源:https://stackoverflow.com/questions/260627/selected-entry-in-a-drop-down-select-html-form-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!