33

我想检查每个组的第一个单选按钮。但是有一些单选按钮被禁用,所以脚本应该忽略它们并转到下一个非禁用按钮。

我写了这样的东西,但它不起作用:

$(文档).ready(函数(){
if ($("input['radio']).is(':disabled'))
    {  
        $(this).attr('checked', false );
    }
别的
    {
        $(this).attr('checked', true );
    }
});

非常感谢

4

9 回答 9

73

如果您的按钮按其名称属性分组,请尝试:

$("input:radio[name=groupName][disabled=false]:first").attr('checked', true);

如果它们按父容器分组,则:

$("#parentId input:radio[disabled=false]:first").attr('checked', true);
于 2010-10-20T12:34:17.633 回答
18
$("input:radio[name=groupX]:not(:disabled):first")

这应该为您提供组中的第一个非禁用单选按钮......

于 2010-10-20T12:28:50.487 回答
8

下面做你想要的:

$(document).ready(
  function(){
    $('input:radio:first-child').attr('checked',true);
  }
  );

演示在:JS Bin

于 2010-10-20T12:27:01.737 回答
3
<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/

于 2010-10-20T12:44:35.797 回答
3

我测试了第一个答案,但没有解决。我不得不使用以下句子:

jQuery("input:radio[name=groupName]:visible")[0].checked=true;

这会检查第一个可见的单选按钮 name = groupName

于 2019-06-06T14:23:15.393 回答
1

尝试这个 :

 $("input:radio:not(:disabled)").attr("checked", true);

要仅检查组中的第一个单选按钮,您可以

 $("parentelement input:radio:not(:disabled):first-child").attr("checked", true);
于 2010-10-20T12:26:52.853 回答
1

如果你有这门课并且你不关心禁用的物品,那就这样做

$(".className").first().click();

或者干脆

$(".className").first().prop("checked", true);
于 2022-01-15T17:20:23.257 回答
1

这使得默认情况下检查第一个无线电

jQuery("input:radio[name=groupName]").first().click()
于 2021-02-21T11:17:41.290 回答
1

2020年的小升级。官方文档建议使用“first()”和“prop()”

$("input[name='groupName'][disabled=false]").first().prop("checked", true);
于 2020-07-10T02:54:15.843 回答