Reputation: 838
I have a html select box with a list of countries. When I select one, it posts to the PHP method with no problem, but the select box resets to the top. How can I preserve the value that the user selected here? My code is here (for brevity's sake, I've taken out most of the other countries)
<html>
<body>
<form action="" method="post">
<select name="countryCd" onChange="submit();return false;">
<option value="AFG">Afghanistan</option>
<option value="ALA">Aland Islands</option>
<option value="ALB">Albania</option>
</select>
</form>
<?php echo $_POST["countryCd"]; ?>
</body>
</html>
Upvotes: 3
Views: 10725
Reputation: 483
You may find this question useful:
Keep form values after submit PHP
Essentially you can use something like:
<select name="countryCD">
<option value="AFG"
<?php if(isset($_POST['countryCD']) && $_POST['countryCD'] == 'AFG')
echo 'selected= "selected"';
?>
>Afghanistan</option>
</select>
Upvotes: 8
Reputation: 231
Add the following to each OPTION. You will need to change this value for each.
<?php if($_POST['countryCd'] == '*this value*'){ php?>selected<?php } php?>
Upvotes: 1
Reputation: 2217
Try:
<select name="countryCd" onChange="submit();return false;">
<option value="AFG" <?= $_POST['countyCd'] == AFG ? 'selected' : '' ?>>Afghanistan</option>
<option value="ALA" <?= $_POST['countyCd'] == ALA ? 'selected' : '' ?>>Aland Islands</option>
<option value="ALB" <?= $_POST['countyCd'] == ALB ? 'selected' : '' ?>>Albania</option>
</select>
Upvotes: 3