使用 JQuery 检查第一个单选按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3977699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check first radio button with JQuery
提问by Matthew
I would like to check the first radio button of each group. But there are some radio button that are disabled, so the script should ignore them and go to next non-disabled button.
我想检查每个组的第一个单选按钮。但是有一些单选按钮被禁用,所以脚本应该忽略它们并转到下一个非禁用按钮。
I wrote something like this but it doesn't work:
我写了这样的东西,但它不起作用:
$(document).ready(function(){ if ($("input['radio']).is(':disabled')) { $(this).attr('checked', false ); } else { $(this).attr('checked', true ); } });
Thanks a lot
非常感谢
回答by sje397
If your buttons are grouped by their name attribute, try:
如果您的按钮按名称属性分组,请尝试:
$("input:radio[name=groupName][disabled=false]:first").attr('checked', true);
If they are grouped by a parent container, then:
如果它们按父容器分组,则:
$("#parentId input:radio[disabled=false]:first").attr('checked', true);
回答by ?ime Vidas
$("input:radio[name=groupX]:not(:disabled):first")
This should give you the first non-disabled radio-button from a group...
这应该为您提供组中第一个未禁用的单选按钮...
回答by David says reinstate Monica
回答by Floyd
<input type="radio" name="r1"><br>
<input type="radio" name="r1"><br>
<hr>
<input type="radio" name="r2"><br>
<input type="radio" name="r2"><br>
<input type="radio" name="r2"><br>
<script>
$(function(){
//removed duplicates form the following array
$(jQuery.unique(
//create an array with the names of the groups
$('INPUT:radio')
.map(function(i,e){
return $(e).attr('name') }
).get()
))
//interate the array (array with unique names of groups)
.each(function(i,e){
//make the first radio-button of each group checked
$('INPUT:radio[name="'+e+'"]:visible:first')
.attr('checked','checked');
});
});
</script>
jsfiddle = http://jsfiddle.net/v4auT/
jsfiddle = http://jsfiddle.net/v4auT/
回答by Andres
I tested the first answer and it doesn't resolve it. I had to use the following sentence:
我测试了第一个答案,但没有解决。我不得不使用以下句子:
jQuery("input:radio[name=groupName]:visible")[0].checked=true;
This check the first visible radio button with name = groupName
这将检查名称 = groupName 的第一个可见单选按钮
回答by rahul
Try this :
尝试这个 :
$("input:radio:not(:disabled)").attr("checked", true);
To check the first radio button only in a group you can
要仅检查组中的第一个单选按钮,您可以
$("parentelement input:radio:not(:disabled):first-child").attr("checked", true);