我有这段代码
<select id="menu" name="department">
<?php
//Get the departments and create the select menu dynamically
include 'connect.php';
$query = "SELECT* FROM department;";
$result = mysqli_query($link,$query);
$html = "";
if($result){
while ($obj = mysqli_fetch_object($result)) {
$html.='<option value="'.$obj->dept_name.'">'.$obj->dept_name.'</option>';
}
} else {$html.='<p style="color:red;text-align:center">Θεμελιώδες λάθος κατά την ανάκτηση των τμημάτων</p>';}
print $html;
mysqli_close($link);
?>
</select>
<?php
if (isset($_POST['menu']))
print '<script type="text/javascript">document.getElementById("menu").value = "'.$_POST['menu'].'";</script>';
?>
嵌套在一个表单标签中,动态创建一个选择菜单,我希望在提交后保留所选的值。它不起作用。有什么想法吗?
答案 0 :(得分:2)
在创建选项的位置动态添加代码以保留select的post值,例如
$html .= '<option value="'.$obj->dept_name.'"';
if(isset($_POST['department']) && $_POST['department'] == $obj->dept_name){
$html .= ' selected ';
}
$html .= '>'.$obj->dept_name.'</option>';