I have an select box:
<select id="selectBox">
<option value="0">Number 0</option>
<option value="1">Number 1</option>
<option value="2">Number 2</option>
<option value="3">Number 3</option>
<option value="4">Number 4</option>
<option value="5">Number 5</option>
<option value="6">Number 6</option>
<option value="7">Number 7</option>
</select>
I'd like to set one of the options as "selected" based on it's selected index.
For example, if I am trying to set "Number 3", I'm trying this:
$('#selectBox')[3].attr('selected', 'selected');
But this doesn't work. How can I set an option as selected based on it's index using jQuery?
Thanks!
This may also be useful, so I thought I'd add it here.
If you would like to select a value based on the item's value and not the index of that item then you can do the following:
Your select list:
The jquery:
The selected item would be "Number 2" now.
I've always had issues with prop('selected'), the following has always worked for me:
Hope this could help Too
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 andidx
is the option value you want selected.NB:
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."