vinman75
vinman75

Reputation: 101

jQuery, .each() and children

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

Answers (5)

Thein Hla Maw
Thein Hla Maw

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

Galled
Galled

Reputation: 4206

Try with:

$('ul#mygroup li select').each(function () {
  $(this).children('option').first().attr('selected', 'selected');
});

Upvotes: 1

SLaks
SLaks

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

Brad Christie
Brad Christie

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

Ry-
Ry-

Reputation: 224867

You don't need .each(); just do this:

$('#mygroup li select option:first-of-type').prop('selected', true);

Upvotes: 5

Related Questions