有选项显示空白,然后在提交保持值选择


Have option display blank then on submit keep value selected

是否可以将下拉列表中的第一项默认为空白并选中,但当在下拉列表中选择一项并点击提交时,该值保留在那里

这里有一个例子

<form action="" method="post" />
<SELECT NAME="whatever" id="whatever">
<?php $selected = isset($_POST["whatever"]) && $_POST["whatever"] == 'whatever'; ?>
<option value="" hidden="true" selected="selected"></option>
<OPTION VALUE=1 onclick"selected='selected'">All</OPTION>
</SELECT> 
<input type="submit" name="submit" value="Update"/>
</form>

当前如果我点击提交,它会把选中的值变回空白

你可以这样使用

<form action="" method="post" />
<SELECT NAME="whatever" id="whatever">
<option value="">Select value</option>
<OPTION VALUE=1 <?php if($_POST["whatever"]==1) echo "selected='selected'";?> >All</OPTION>
<OPTION VALUE=2 <?php if($_POST["whatever"]==2) echo "selected='selected'";?> >Value One</OPTION>
</SELECT> 
<input type="submit" name="submit" value="Update"/>
</form>
function html_select($name, $options, $selected= "")
{
    // open <select> tag, set id & name attributes
    $select = "<select id='"$name'" name='"$name'">'n";
    // populate options to drop down list
    foreach ($options as $value=> $html) {
        $select .= "<option value='"$value'"";
        // select the selected option
        if ($value == $selected) {
            $select .= " selected='"selected'"";
        }
        $select .= ">$html</option>'n";
    }
    // close </select> tag
    $select .= "</select>";
    // return element
    return $select ;
}
echo html_select("whatever", array("" => "Select Value", "1" => "Value 1"), $_POST["whatever"]);