Reputation: 101
I am trying to find and set the first option of many select boxes on a page.
$('ul#mygroup li select').each(function () {
$(this +' option:nth-child(0)').attr('selected', 'selected');
});
The second line is where this is failing at. I can't seem to target the first option of each select box within the group.
Upvotes: 3
Views: 2629
Reputation: 683
Hope this will work for you.
<select name="type1">
<option value="1">Option 1</value>
<option value="2">Option 2</value>
<option value="3">Option 3</value>
</select>
<select name="type2">
<option value="1">Option 1</value>
<option value="2">Option 2</value>
<option value="3">Option 3</value>
</select>
<select name="type3">
<option value="1">Option 1</value>
<option value="2">Option 2</value>
<option value="3">Option 3</value>
</select>
$(function(){
$('select').each(function () {
$(this).children().first().attr('selected', 'selected');
$(this).children().first().attr('style', 'color: blue');
});
});
Upvotes: 0
Reputation: 4206
Try with:
$('ul#mygroup li select').each(function () {
$(this).children('option').first().attr('selected', 'selected');
});
Upvotes: 1
Reputation: 887285
You're misusing selectors.
You need to write $(this).children('option:first-child').attr('selected', true)
.
You can also just write $('ul#mygroup li select').prop('selectedIndex', 0)
.
Upvotes: 3
Reputation: 101604
you shouldn't be concatenating this
, you should be using it for scope.
$('option:first',this).attr('selected','selected');
Or, concisely you're saying (keeping it within the .each
loop)
$(this).find('option:first').attr('selected','selected');
Though, as others have mentioned, there's no need to use the .each
. In fact, nth-child
is specifically there to avoid using an .each
Upvotes: 2
Reputation: 224867
You don't need .each()
; just do this:
$('#mygroup li select option:first-of-type').prop('selected', true);
Upvotes: 5