Choose option 1 from the drop-down list of multiple groups with jquery

My dropdown is 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 the 1st group (bikes here). How do I do this in jQuery?

I have currently tried this:

 $('#someSelect option:nth-child(1)').attr("selected", "selected"); 

BUT , the problem is that there are the first three elements ( --select-- , Hayabusa and Audi TT ) that selects all three that finally select the Audi TT

I tried to do some things with each and select only the second, but then I realized that the dropdown is dynamic, I do not want to select the default value ( --select one-- ), but the first element of the first group

I tried to imitate jsfiddle, but it worked and did not work, not sure why: - /
you can see it here

+4
source share
7 answers

Here is an example and here is the selector that I used:

 $("#someSelect optgroup option:first").attr("selected", "selected"); 

As you can see, I used the first option by looking at the optgroup element.

+6
source

Well it works:

http://jsfiddle.net/nYd67/1/

 $(function(){ $('#someSelect optgroup:eq(0) option:eq(0)').attr("selected", "selected"); }); 
+4
source

select from optgroup instead of select:

 $('optgroup[label=Bikes] option:first') 

Or, if you do not want to specify a label, just filter also in optgroup:

 $('optgroup:first option:first') 
+4
source

Just include optgroup in your selector:

 $('#someSelect optgroup:nth-child(2) option:nth-child(1)') 

Just remember that the :nth-child() selector is based on 1, not 0. Also, in this case you don’t even need to qualify the selector with the tag name, so it can also be simple:

 $('#someSelect :nth-child(2) :nth-child(1)') 
+3
source

I always find .eq() lot easier to use. This seems to work correctly in your jsfiddle.

 $('#someSelect option').eq(1).attr("selected", "selected"); 
+2
source
 $('#someSelect optgroup:first option:first').attr('selected', true); 

this works, i tested on your html

+2
source

The selector for the first option in the first optgroup of the select element with the identifier "someSelect":

 "select#someSelect > optgroup:nth-child(1) > option:nth-child(1)" 
+1
source

All Articles