How to preselect option in select box using jQuery
44,804
Solution 1
When the page loads run this (you can put it in <body onload="//put code here">
):
$("option[value='10']").attr('selected','selected');
Solution 2
Test the example: http://jsfiddle.net/VArCZ/
$(document).ready(function() {
$('#mySelectBox').val('10');
});
Although, jQuery wouldn't be required for this if the intial value will be static:
<select id='mySelectBox'>
<option value='5'>5</option>
<option value='10' selected='selected'>10</option>
<option value='15'>15</option>
</select>
Solution 3
In the latest jQuery version this works for me:
$("option[value='10']").prop('selected',true);
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Author by
Admin
Updated on October 13, 2020Comments
-
Admin over 3 years
I have one select box with various options.
When a page loads then one option with a value, for example 10, should be preselected with jQuery.
How can I do that?
-
user113716 about 14 yearsYou'll need to remove the descendant operator (space) from the selector for it to work. :o)
-
Doug Neiner about 14 years+1 Correct of course! I might add that with
.val()
you supply the value between the<option></option>
tags, not thevalue=
attribute. So in the case of<option value="10">Ten</option>
you would use$("#mySelectBox").val('Ten')
-
Funka about 14 years+1 I prefer this approach more so than using
val()
to set these. I'm not even sure howval()
is supposed to work if you are presenting a multiple-select listbox... -
user113716 about 14 years@Doug - Actually, if there is a value attribute present, it matches against that first. If no value attribute, then it tries to match against the text content. But thanks for the +1. :o) updated example: jsfiddle.net/VArCZ/1
-
user113716 about 14 years@Funka - If it is a multiple select, it will accept an array of values to set. example jsfiddle.net/VArCZ/2
-
Doug Neiner about 14 yearsDude.. seriously? I always thought that method was #fail... I need to read the source more. Thanks!
-
user113716 about 14 years@Doug - Full disclosure: I had to do a quick scramble to make sure I had it right. Happens more often than I care to admit. :o)
-
jafar pinjar over 5 years@Adam, how to select it based on the select id?
-
Adam over 5 yearsJust use
$("#myId")