Simpliest way to remember DropDown selection?

巧了我就是萌 提交于 2019-12-12 04:33:26

问题


I have;

<form method="post" action="search.php">
  <select name="country">
    <option value="">Select Country</option>   
    <option value="Afghanistan">Afghanistan</option>
    <option value="Albania">Albania</option>
  </select>
</form>

And then in search.php $country = $country query MySQL table for column that's %like% country.

I wonder what is the simplest way to remember dropdown selection after someone makes pick up country?


回答1:


You want to be using the selected attribute on the option element. If you're populating the select element from an array or database query, you can do this:

<?php foreach($countries as $country): ?>
<option value="<?php echo $country ?>"<?php if($_POST['country'] == $country) { echo ' selected="selected"'; } ?>><?php echo $country ?></option>
<?php endforeach ?>

Also, as a side note it's better to assign $country as follows:

$country = $_POST['country'];



回答2:


Whatever you're doing on the server side, your rendered HTML should use the attribute selected="selected" on the <option> you want it to be initially selected.



来源:https://stackoverflow.com/questions/12782116/simpliest-way-to-remember-dropdown-selection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!