使用$ _POST值选择下拉列表

时间:2016-05-13 15:28:34

标签: javascript php jquery

我有一个像这样的下拉菜单

    <form method="post">
            Filter by state:
            <select name="state" id="state">

                <option value=""></option>
                <option value="AL">Alabama</option><option value="AK">Alaska</option>
                <option value="AZ">Arizona</option><option value="AR">Arkansas</option>
                <option value="CA">California</option><option value="CO">Colorado</option>
                <option value="WY">Wyoming</option><option value="Other">Other</option>
                <input type="submit" id="statefilt" name="statefilt" onclick="" value="Submit" />
            </select>
        </form>

当重新加载页面时,我得到$ _POST

Array ([state]=>AL [statefilt]=>Submit)

有没有办法使用$_POST['state'],如果值不为空,则选择该选项?

1 个答案:

答案 0 :(得分:2)

You can use selected attribute when the $_POST value is same as <option> value.

And, <input type="submit" id="statefilt" name="statefilt" onclick="" value="Submit" /> is wrong inside <select></select>

<form method="post">
  Filter by state:
  <select name="state" id="state">
      <option value="" <?if($_POST['state'] == ""){echo "selected";}?>></option>
      <option value="AL" <?if($_POST['state'] == "AL"){echo "selected";}?>>Alabama</option>
      <option value="AK" <?if($_POST['state'] == "AK"){echo "selected";}?>>Alaska</option>
      <option value="AZ" <?if($_POST['state'] == "AZ"){echo "selected";}?>>Arizona</option>
      <option value="AR" <?if($_POST['state'] == "AR"){echo "selected";}?>>Arkansas</option>
  </select>
  <input type="submit" id="statefilt" name="statefilt" onclick="" value="Submit" />
</form>