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 badges5 Answers
Reset to default 5You 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
版权声明:本文标题:javascript - jQuery, .each() and children - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741501707a2382087.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论