我想检查每个组的第一个单选按钮。但是有一些单选按钮被禁用,所以脚本应该忽略它们并转到下一个非禁用按钮。
我写了这样的东西,但它不起作用:
$(文档).ready(函数(){ if ($("input['radio']).is(':disabled')) { $(this).attr('checked', false ); } 别的 { $(this).attr('checked', true ); } });
非常感谢
我想检查每个组的第一个单选按钮。但是有一些单选按钮被禁用,所以脚本应该忽略它们并转到下一个非禁用按钮。
我写了这样的东西,但它不起作用:
$(文档).ready(函数(){ if ($("input['radio']).is(':disabled')) { $(this).attr('checked', false ); } 别的 { $(this).attr('checked', true ); } });
非常感谢
如果您的按钮按其名称属性分组,请尝试:
$("input:radio[name=groupName][disabled=false]:first").attr('checked', true);
如果它们按父容器分组,则:
$("#parentId input:radio[disabled=false]:first").attr('checked', true);
$("input:radio[name=groupX]:not(:disabled):first")
这应该为您提供组中的第一个非禁用单选按钮......
下面做你想要的:
$(document).ready(
function(){
$('input:radio:first-child').attr('checked',true);
}
);
演示在:JS Bin。
<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/
我测试了第一个答案,但没有解决。我不得不使用以下句子:
jQuery("input:radio[name=groupName]:visible")[0].checked=true;
这会检查第一个可见的单选按钮 name = groupName
尝试这个 :
$("input:radio:not(:disabled)").attr("checked", true);
要仅检查组中的第一个单选按钮,您可以
$("parentelement input:radio:not(:disabled):first-child").attr("checked", true);
如果你有这门课并且你不关心禁用的物品,那就这样做
$(".className").first().click();
或者干脆
$(".className").first().prop("checked", true);
这使得默认情况下检查第一个无线电
jQuery("input:radio[name=groupName]").first().click()
2020年的小升级。官方文档建议使用“first()”和“prop()”
$("input[name='groupName'][disabled=false]").first().prop("checked", true);