Simpliest way to remember DropDown selection?

2019-08-31 12:09发布

问题:

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.