在表单提交后保留所选值

2022-08-30 12:23:15

考虑:

<form method="get" action="">
   <select name="name">
      <option value="a">a</option>
      <option value="b">b</option>
   </select>
   <select name="location">
      <option value="x">x</option>
      <option value="y">y</option>
   </select>
   <input type="submit" value="Submit" class="submit" />
</form>

提交表单时,如何确保所选值在下拉列表中保持选中状态?此表单位于WordPress(PHP)中。


答案 1

为了避免许多 if-else 结构,让 JavaScript 自动执行该操作:

<select name="name" id="name">
   <option value="a">a</option>
   <option value="b">b</option>
</select>

<script type="text/javascript">
  document.getElementById('name').value = "<?php echo $_GET['name'];?>";
</script>

<select name="location" id="location">
  <option value="x">x</option>
  <option value="y">y</option>
</select>

<script type="text/javascript">
  document.getElementById('location').value = "<?php echo $_GET['location'];?>";
</script>

答案 2
<select name="name">
   <option <?php if ($_GET['name'] == 'a') { ?>selected="true" <?php }; ?>value="a">a</option>
   <option <?php if ($_GET['name'] == 'b') { ?>selected="true" <?php }; ?>value="b">b</option>
</select>