To clarify Marc's and John Kugelman's answers, you could use:
$('#selectBox option').eq(3).attr('selected', 'selected')
get()
will not work if used in the way specified because it gets the DOM object, not a jQuery object, so the following solution will not work:
$('#selectBox option').get(3).attr('selected', 'selected')
eq()
gets filters the jQuery set to that of the element with the specified index. It's clearer than $($('#selectBox option').get(3))
. It's not all that efficient. $($('#selectBox option')[3])
is more efficient (see test case).
You don't actually need the jQuery object though. This will do the trick:
$('#selectBox option')[3].selected = true;
http://api.jquery.com/get/
http://api.jquery.com/eq/
The attribute "selected" is not how you specify a selected radio button (in Firefox and Chrome at least). Use the "checked" attribute:
$('#selectBox option')[3].checked = true;
The same goes for check-boxes.
What's important to understand is that val()
for a select
element returns the value of the selected option, but not the number of element as does selectedIndex
in javascript.
To select the option with value="7"
you can simply use:
$('#selectBox').val(7); //this will select the option with value 7.
To deselect the option use an empty array:
$('#selectBox').val([]); //this is the best way to deselect the options
And of course you can select multiple options*:
$('#selectBox').val([1,4,7]); //will select options with values 1,4 and 7
*However to select multiple options, your <select>
element must have a MULTIPLE
attribute, otherwise it won't work.
I need a solution that has no hard coded values in the js file; using selectedIndex
. Most of the given solutions failed one browser. This appears to work in FF10 and IE8 (can someone else test in other versions)
$("#selectBox").get(0).selectedIndex = 1;
You can also init multiple values if your selectbox is a multipl:
$('#selectBox').val(['A', 'B', 'C']);
In 1.4.4 you get an error: $("#selectBox option")[3].attr is not a function
This works: $('#name option:eq(idx)').attr('selected', true);
Where #name
is select id and idx
is the option value you want selected.
NB:
$('#selectBox option')[3].attr('selected', 'selected')
is incorrect, the array deference gets you the dom object, not a jquery object, so it will fail with a TypeError, for instance in FF with: "$('#selectBox option')[3].attr() not a function."