jQuery Set Select Index
Solution 1:
NOTE: answer is dependent upon jQuery 1.6.1+
$('#selectBox :nth-child(4)').prop('selected', true); // To select via index
$('#selectBox option:eq(3)').prop('selected', true); // To select via value
Thanks for the comment, .get
won't work since it returns a DOM element, not a jQuery one. Keep in mind the .eq
function can be used outside of the selector as well if you prefer.
$('#selectBox option').eq(3).prop('selected', true);
You can also be more terse/readable if you want to use the value, instead of relying on selecting a specific index:
$("#selectBox").val("3");
Note: .val(3)
works as well for this example, but non-numeric values must be strings, so I chose a string for consistency.
(e.g. <option value="hello">Number3</option>
requires you to use .val("hello")
)
Solution 2:
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');
$('#selectBox option[value=C]').prop('selected', true);
The selected item would be "Number 2" now.