doulu4203 2019-05-11 10:00
浏览 398
已采纳

如何在PHP中的动态下拉列表中显示选定的值

I am trying to retain the value selected in a drop down menu. Everything is working, but I don't know how to show and retain the selected value. How can I do this?

I've got this working using another way:

<?php if($_POST['selClass'] == $row1['class']) echo 'selected="selected"' ?>

but this leads to other problems, i.e. a blank option in my drop down menu.

<form action="" method="POST" name="form1" id="form1">
<select name="selClass" size="1" id="selClass" onchange="form1.submit()">
<option value="">Select a class</option>
<?php
echo "<option value='". "All records". "' . >" . "all records". "</option>";
while ($row1 = mysqli_fetch_array($rs5)) {
echo "<option value='".$row1["class"] ."'>" . $row1["class"]. "</option>";
}
?>
</select>
</form>
  • 写回答

2条回答 默认 最新

  • douce1368 2019-05-11 10:04
    关注

    You can approach this as

    <?php
    $selectedOption = '';
    if($_POST){
     $selectedOption = $_POST['selClass'];
    }
    ?>
    <form action="" method="POST" name="form1" id="form1">
    <select name="selClass" size="1" id="selClass" onchange="form1.submit()">
    <option value="">Select a class</option>
    <?php
        echo "<option value='". "All records". "' . >" . "all records". "</option>";
        while ($row1 = mysqli_fetch_array($rs5)) {
            if($row1["class"] == $selectedOption)
                echo "<option value='".$row1["class"] ."' selected='selected'>" . $row1["class"]. "</option>";
            else
                echo "<option value='".$row1["class"] ."'>" . $row1["class"]. "</option>";
        }
    ?>
     </select>
    </form>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?