views:

7800

answers:

4

Hello,

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!

+9  A: 

You've selected the <select>, not the <option>s inside of it.

$('#selectBox option')[3].attr('selected', 'selected')
John Kugelman
Thanks very much. +1 to Marc for providing some other methods which were also quite useful.
+1  A: 

Try this instead:

$("#selectBox).val(3);

also, see if this helps you:

http://elegantcode.com/2009/07/01/jquery-playing-with-select-dropdownlistcombobox/

Chris Brandsma
+12  A: 
$('#selectBox option:nth-child(3)').attr('selected', 'selected')
$('#selectBox option:eq(3)').attr('selected', 'selected')
$('#selectBox option').get(3).attr('selected', 'selected')

Should all work in addition to what John put

Marc
+3  A: 

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:

<select id="selectBox">
<option value="A">Number 0</option>
<option value="B">Number 1</option>
<option value="C">Number 2</option>
<option value="D">Number 3</option>
<option value="E">Number 4</option>
<option value="F">Number 5</option>
<option value="G">Number 6</option>
<option value="H">Number 7</option>
</select>

The jquery:

$('#selectBox option[value=C]').attr('selected', 'selected');

The selected item would be "Number 2" now.

dnoxs
note: there's an extra underscore after the $()... otherwise, this works fantastically
Dusty J