Consider:
<form method="get" action="">
<select name="name">
<option value="a">a</option>
<option value="b">b</option>
</select>
<select name="location">
<option value="x">x</option>
<option value="y">y</option>
</select>
<input type="submit" value="Submit" class="submit" />
</form>
On submitting the form, how do I make sure that the selected values remain selected in the dropdowns? This form is inside WordPress (PHP).
To avoid many if-else structures, let JavaScript do the trick automatically:
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.If you are using WordPress (as is the case with the OP), you can use the
selected
function.Since WordPress already uses jQuery you can try something like this:
JavaScript only solution:
Or if you are using jQuery you can replace
with:
Try this solution for keep selected value in dropdown:
This works for me!
Just change this line:
with this line:
I don’t work in WordPress much, but for forms outside of WordPress, this works well.
PHP
HTML
We can create an array of option before hand and only use simple if/else to check if selected or not. If you want different values for data and different value for displaying option you can use associative arrays too.