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")
)
I faced same problem. First you need go through the events (i.e which event is happening first).
For example:
The First event is generating select box with options.
The Second event is selecting default option using any function such as val() etc.
You should ensure that the Second event should happen after the First event.
To achieve this take two functions lets say generateSelectbox() (for genrating select box) and selectDefaultOption()
You need to ensure that selectDefaultOption() should be called only after the execution of generateSelectbox()
Select the item based on the value in the select list (especially if the option values have a space or weird character in it) by simply doing this:
$("#SelectList option").each(function () {
if ($(this).val() == "1:00 PM")
$(this).attr('selected', 'selected');
});
Also, if you have a dropdown (as opposed to a multi-select) you may want to do a break;
so you don't get the first-value-found to be overwritten.
Try this instead:
$("#selectBox").val(3);
The pure javascript selectedIndex attribute is the right way to go because,it's pure javascript and works cross-browser:
$('#selectBox')[0].selectedIndex=4;
Here is a jsfiddle demo with two dropdowns using one to set the other:
<select onchange="$('#selectBox')[0].selectedIndex=this.selectedIndex">
<option>0</option>
<option>1</option>
<option>2</option>
</select>
<select id="selectBox">
<option value="0">Number 0</option>
<option value="1">Number 1</option>
<option value="2">Number 2</option>
</select>
You can also call this before changing the selectedIndex if what you want is the "selected" attribute on the option tag (here is the fiddle):
$('#selectBox option').removeAttr('selected')
.eq(this.selectedIndex).attr('selected','selected');
Hope this could help Too
$('#selectBox option[value="3"]').attr('selected', true);