如何使用 php 预选 html 下拉列表?

新手上路,请多包涵

我正在尝试使用 PHP 选择该选项,但我没有想法!

以下是我到目前为止尝试过的代码:

 <select>
<option value="1">Yes</options>
<option value="2">No</options>
<option value="3">Fine</options>
</select>
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">

那么,我该怎么办?

原文由 artur 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 309
1 个回答

这是我想出的解决方案:

 <form name = "form1" id = "form1" action = "#" method = "post">
  <select name = "DropDownList1" id = "DropDownList1">
<?php
$arr = array('Yes', 'No', 'Fine' ); // create array so looping is easier
for( $i = 1; $i <= 3; $i++ ) // loop starts at first value and ends at last value
{
  $selected = ''; // keep selected at nothing
  if( isset( $_POST['go'] ) ) // check if form was submitted
  {
    if( $_POST['DropDownList1'] == $i ) // if the value of the dropdownlist is equal to the looped variable
    {
      $selected = 'selected = "selected"'; // if is equal, set selected = "selected"
    }
  }
  // note: if value is not equal, selected stays defaulted to nothing as explained earlier
  echo '<option value = "' . $i . '"' . $selected . '>' . $arr[$i] . '</option>'; // echo the option element to the page using the $selected variable
}
?>
  </select> <!-- finish the form in html -->
  <input type="text" value="" name="name">
  <input type="submit" value="go" name="go">
</form>

只要值是某种数字顺序(升序或降序)的整数,我的代码就可以工作。它的作用是在 html 中启动下拉列表,并在 php 代码中添加每个选项元素。但是,如果您有随机值,则它将不起作用,即:1、4、2、7、6。每个值必须是唯一的。

原文由 Vince 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题