Keep values selected after form submission
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>
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>
If you are using WordPress (as is the case with the OP), you can use the selected
function.
<form method="get" action="">
<select name="name">
<option value="a" <?php selected( isset($_POST['name']) ? $_POST['name'] : '', 'a' ); ?>>a</option>
<option value="b" <?php selected( isset($_POST['name']) ? $_POST['name'] : '', 'b' ); ?>>b</option>
</select>
<select name="location">
<option value="x" <?php selected( isset($_POST['location']) ? $_POST['location'] : '', 'x' ); ?>>x</option>
<option value="y" <?php selected( isset($_POST['location']) ? $_POST['location'] : '', 'y' ); ?>>y</option>
</select>
<input type="submit" value="Submit" class="submit" />
</form>
<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>