Keep values selected after form submission Keep values selected after form submission wordpress wordpress

Keep values selected after form submission


To avoid many if-else structures, let JavaScript do the trick automatically:

<select name="name" id="name">   <option value="a">a</option>   <option value="b">b</option></select><script type="text/javascript">  document.getElementById('name').value = "<?php echo $_GET['name'];?>";</script><select name="location" id="location">  <option value="x">x</option>  <option value="y">y</option></select><script type="text/javascript">  document.getElementById('location').value = "<?php echo $_GET['location'];?>";</script>


<select name="name">   <option <?php if ($_GET['name'] == 'a') { ?>selected="true" <?php }; ?>value="a">a</option>   <option <?php if ($_GET['name'] == 'b') { ?>selected="true" <?php }; ?>value="b">b</option></select>


After trying all these "solutions", nothing work. I did some research on W3Schools before and remember there was explanation of keeping values about radio.

But it also works for the Select option. See below for an example. Just try it out and play with it.

<?php    $example = $_POST["example"];?><form method="post">    <select name="example">        <option <?php if (isset($example) && $example=="a") echo "selected";?>>a</option>        <option <?php if (isset($example) && $example=="b") echo "selected";?>>b</option>        <option <?php if (isset($example) && $example=="c") echo "selected";?>>c</option>    </select>    <input type="submit" name="submit" value="submit" /></form>