I want to set a option that was selected previously to be displayed on page load. I tried it with the following code:
$("#gate").val('Gateway 2');
with
<select id="gate">
<option value='null'>- choose -</option>
<option value='Gateway 1'>Gateway 1</option>
<option value='Gateway 2'>Gateway 2</option>
</select>
But this does not work. Any ideas?
That works fine. See this fiddle: http://jsfiddle.net/kveAL/
It is possible that you need to declare your jQuery in a
$(document).ready()
handler?Also, might you have two elements that have the same ID?
I had the same problem.
Solution: add a refresh.
I know there are several iterations of answers but now this doesn't require jquery or any other external library and can be accomplished pretty easy just with the following.
I have found using the jQuery .val() method to have a significant drawback.
If this select box (or any other input object) is in a form and there is a reset button used in the form, when the reset button is clicked the set value will get cleared and not reset to the beginning value as you would expect.
This seems to work the best for me.
For Select boxes
For text inputs
For textarea inputs
For checkbox boxes
For radio buttons
Addition to @icksde and @Korah (thx both!)
When building the options with AJAX the document.ready may be triggered before the list is built, so
This doesn't work
This does
A timeout does work but as @icksde says it's fragile (I did actually need 20ms in stead of 10ms). It's better to fit it inside the AJAX function like this: