2010-10-20 67 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