I have dropdown very similar to this:
<select id='someSelect'>
<option value="0">---select one---</option>
<optgroup label="Bikes">
<option value="B-4">Hayabusa</option>
<option value="B-2">GSXR</option>
<option value="B-3">Ninja</option>
<option value="B-6">Enticer</option>
</optgroup>
<optgroup label="Cars">
<option value="C-4">Audi TT</option>
<option value="C-2">Awesome Car</option>
<option value="C-23">Japanese car</option>
<option value="C-9">German car</option>
</optgroup>
</select>
I just want to select the 1st element of 1st group (bikes here). How do I go about it in jQuery please?
Currently, I tried this:
$('#someSelect option:nth-child(1)').attr("selected", "selected");
BUT, the trouble is, since there are three 1st elements ( --select--
, Hayabusa
and Audi TT
) it selects all three, which finaly selects Audi TT
I tried to do some stuff with each
and select just the second one, but then I realized that the dropdown is dynamic, I don't want to select the default one (which is --select one--
) but the first element of first group
I tried to mock up a jsfiddle, but it's mucked up and not working, not sure why :-/
you can see it here
Select first element of <select> element using JQuery selector. Use . prop() property to get the access to properties of that particular element. Change the selectedIndex property to 0 to get the access to the first element.
We will use the MultiSelect Plugin to implement multiselect dropdown with checkbox in jQuery. In order to implement a multi-select dropdown list with checkboxes, you need to include the plugin library files. Include the jQuery library and the JS & CSS library of the jQuery MultiSelect plugin.
Projects In JavaScript & JQuery With jQuery, it's easy to get selected text from a drop-down list. This is done using the select id. To change the selected value of a drop-down list, use the val() method.
With jQuery, you can use the . val() method to get an array of the selected values on a multi-select dropdown list.
Here is an example and here is the selector I used:
$("#someSelect optgroup option:first").attr("selected", "selected");
As you can see, I used the first option by looking inside the optgroup element.
Well this works:
http://jsfiddle.net/nYd67/1/
$(function(){
$('#someSelect optgroup:eq(0) option:eq(0)').attr("selected", "selected");
});
select from the optgroup instead of the select:
$('optgroup[label=Bikes] option:first')
Or, if you don't want to specify the label, just filter on the optgroup as well:
$('optgroup:first option:first')
Just include the optgroup in your selector:
$('#someSelect optgroup:nth-child(2) option:nth-child(1)')
Just remember that the :nth-child()
selector is 1-based, not 0-based. Also, in this case, you don't even need to qualify the selector with a tag name, so it could also be just:
$('#someSelect :nth-child(2) :nth-child(1)')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With