选中/取消选中所有复选框 [英] Check/Uncheck all checkboxes
问题描述
我看到过许多勾选/取消勾选所有核取方块的脚本。但是大多数人不尊重,如果我使用选中所有 - 复选框切换所有复选框,然后取消选中列表中的一个,选中所有复选框仍然选中。
有一种优雅的方式来处理这种情况吗?
<$ c $ p> ('#checkAll')。click(function(){
if(this.checked){
$('input:checkbox')。attr('checked',true);
}
else {
$('input:checkbox')removeAttr('checked');
}
});
$('input:checkbox:not(#checkAll)')click(function(){
if(!this.checked){
$ ').removeAttr('checked');
}
else {
var numChecked = $('input:checkbox:checked:not(#checkAll)')。length;
var numTotal = $('input:checkbox:not(#checkAll)')。length;
if(numTotal == numChecked){
$('#checkAll')。attr('checked' ,true);
}
}
});
演示: http://jsfiddle.net/ThiefMaster/HuM4Q/
如问题的注释中所指出的,常规复选框不是完美的。一旦未选中一个复选框,我的实施就会停用全部检查框。因此,要取消选中所有仍选中的复选框,您必须单击两次(首先重新选中未选中的复选框,然后取消选中所有其他复选框)。
然而,使用三态复选框这可能仍然是必要的,因为状态顺序可能未被选中 - > indefinite-> checked-> unchecked,所以你需要两次点击来自不确定到未选中。 p>
由于您可能不想使用全部检查检查页面上的所有复选框,请将 input:checkbox
用eg .autoCheckBox
或 input.autoCheckBox:checkbox
,并给予这些复选框 class =autoCheckBox
。
如果你想要所有的复选框在一个特定的形式,简单使用 #idOfYourForm input:checkbox
或 form [name = nameOfYourForm]输入:checkbox
I've seen many check/uncheck all checkboxes scripts. But far most does not respect that if I toggled all checkboxes using the "checked all"-checkbox and then uncheck a single one in the list, the "checked all" checkbox is still checked.
Is there an elegant way of handling this case?
$('#checkAll').click(function() {
if(this.checked) {
$('input:checkbox').attr('checked', true);
}
else {
$('input:checkbox').removeAttr('checked');
}
});
$('input:checkbox:not(#checkAll)').click(function() {
if(!this.checked) {
$('#checkAll').removeAttr('checked');
}
else {
var numChecked = $('input:checkbox:checked:not(#checkAll)').length;
var numTotal = $('input:checkbox:not(#checkAll)').length;
if(numTotal == numChecked) {
$('#checkAll').attr('checked', true);
}
}
});
Demo: http://jsfiddle.net/ThiefMaster/HuM4Q/
As pointed out in the question's comment, a regular checkbox is not perfect for this. My implementation disables the "check all" box as soon as one checkbox is unchecked. So, to uncheck all still-checked checkboxes you'll have to click twice (first to re-check the unchecked ones and then to uncheck all other ones). However, with a tri-state checkbox this might still be necessary as the state order might be unchecked->indefinite->checked->unchecked, so you'd need two clicks to come from indefinite to unchecked.
Since you probably don't want to check ALL checkboxes on your page with "Check All", replace input:checkbox
with e.g. .autoCheckBox
or input.autoCheckBox:checkbox
and give those checkboxes class="autoCheckBox"
.
If you want all checkboxes inside a certain form, simple use #idOfYourForm input:checkbox
or form[name=nameOfYourForm] input:checkbox
这篇关于选中/取消选中所有复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!