2010-10-20 68 views
25

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

我写了这样的事情,但它不工作:

$(document).ready(function(){ 
if ($("input['radio']).is(':disabled')) 
    { 
     $(this).attr('checked', false); 
    } 
else 
    { 
     $(this).attr('checked', true); 
    } 
});

非常感谢

+0

input [type = radio] instead – 2010-10-20 12:24:25

+1

**或**,@Haim,'input:radio'。 – 2010-10-20 12:30:08

回答

49

如果你的按钮被他们的名字属性进行分组,请尝试:

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

如果他们

$("#parentId input:radio[disabled=false]:first").attr('checked', true); 
+1

如果您想要更改事件触发,请执行'.click()'而不是 – Yarin 2013-09-22 23:51:36

0

试试这个:

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

要只在一组选中第一个单选按钮你可以

$("parentelement input:radio:not(:disabled):first-child").attr("checked", true); 
+1

我相信OP的意思是“组”,就像“共享相同名称属性的所有单选按钮” – 2010-10-20 12:32:43

+0

“第一个孩子”是不对的 – sje397 2010-10-20 12:38:22

8

下面你想要做什么:JS Bin:在

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

演示。

+0

尽管@Šime和@rahul都提供了明智的理智 - 检查。 – 2010-10-20 12:31:13

+0

'第一个孩子'不正确 – sje397 2010-10-20 12:39:00

+0

$('input:radio:first-child')选择页面中任何一个收音机组的第一个单选按钮。 – 2012-04-12 19:23:47

16
$("input:radio[name=groupX]:not(:disabled):first") 

这应该给你从一组的第一个非残疾人单选按钮...

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> 
:由一个父容器,然后被分组210

jsfiddle = http://jsfiddle.net/v4auT/

+0

Nice Solution(y) – 2016-04-01 08:16:25