Preserving a select option after PHP submit

forms, html, php

Solution

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>

Problem

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> ```

Original source