I am trying to change the selected option for a group of html select elements. I have given them all the same class so that I could use jQuery to select them all at once, but for some reason it only changes the first element in the class. Here is a demo: http://jsfiddle.net/bwhitney/xP4FP/1/
Here is just the code:
<select id="config1" class="config">
<option>foo</option>
<option selected>bar</option>
</select>
<select id="config2" class="config">
<option>foo</option>
<option selected>bar</option>
</select>
<select id="config3" class="config">
<option>foo</option>
<option selected>bar</option>
</select>
With the jQuery:
$('.config option:eq(0)').attr('selected', 'selected');
The result of this code is that only the first select element will have the foo option selected. The second and third will still have bar selected. I thought that using jQuery to select a class would select all items having that class. Is there some way to select all three of these with one selector?
As a pre-emptive response to a likely answer (I’m sure someone will think to suggest this):
I know that I can just write a for loop to select each $('#config' + i). This is what I will end up doing if there is no way to just select them all at once.
Try using
nth-child:Example: http://jsfiddle.net/K4mnx/