2013-08-16 23 views
1

我正在选中全部/无复选框。但是,它只能工作一次:它可以检查所有内容,然后取消全部检查,但不能再次检查所有内容。jquery:全选/无复选框只能工作一次

http://jsfiddle.net/SDEwB/

check all/none: <input type = "checkbox" id = "check_all_none"></input> 
<br/> 
<input type = "checkbox" class = "others"></input><br/> 
<input type = "checkbox" class = "others"></input> 


$('#check_all_none').change(function() { 
    if ($(this).is(':checked')){ 
     $('.others').attr("checked", true); 
    } 
    else{ 
     $('.others').removeAttr("checked"); 
     // $('.others').attr("checked", false); // tried this, too 
    } 
}); 

回答

4

试试这个

$('#check_all_none').click(function() { 
if ($(this).is(':checked')){ 
    $('.others').prop("checked", true); 
} 
else{ 
    $('.others').removeAttr("checked"); 
} 

}); 

Demo

+0

完美!谢谢。 – user984003

1

使用prop代替attr的。

if ($(this).is(':checked')){ 
    $('.others').prop("checked", true); 
} 
else{ 
    $('.others').prop("checked", false); 
} 

http://jsfiddle.net/SDEwB/3/

更新

像阿伦说,这是更好的:

$('#check_all_none').change(function() { 
    $('.others').prop("checked", this.checked); 
}); 
6

使用

$('#check_all_none').change(function() { 
    $('.others').prop("checked", this.checked); 
}); 

演示:Fiddle

0

这里一个简单的方法来检查所有想复选框:

$("#check_all_none").click(function() { 
    $(".others").attr('checked', this.checked); 
}); 

DEMO

0
<input type = "checkbox" id = "check_all_none" onclick="checkAll(this)" /> 
<input type = "checkbox" class = "others" name="chk" /><br/> 
<input type = "checkbox" class = "others" name="chk" /> 

JQuery的:

function checkAll(t){ 
    if ($(t).is(':checked')){ 
     $('.others').prop("checked", true); 
    } 
    else{ 
     $('.others').attr('checked', false); 
    } 
} 

JavaScript:

function checkAll(t){ 
    var checkboxes= document.getElementsByName('chk'); 
    for (var i = 0; i < checkboxes.length; i++) { 
     if(t.checked==true){ 
      checkboxes[i].checked = true; 
     }else{ 
      checkboxes[i].checked = false; 
     } 
    } 
} 

我有声明函数。因为您可以在任何地方轻松地重用此代码。我写了两种类型的代码(JQuery和JavaScript)。两者都正常工作。如果你不需要使用任何jQuery库,那么使用JavaScript代码。

+0

解释一下你的答案。 – arulmr

相关问题