admin管理员组

文章数量:1291061

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.

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.

Share Improve this question asked Nov 15, 2011 at 16:37 vinman75vinman75 1013 silver badges11 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 5

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

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

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).

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

Try with:

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

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');
    });
});

本文标签: JavaScriptJQueryeach() and childrenStack Overflow