jQuery 检查是否所有复选框都被选中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5541387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if all checkboxes are selected
提问by santa
How do I check if all checkboxes with class="abc"
are selected?
如何检查是否选中了所有复选框class="abc"
?
I need to check it every time one of them is checked or unchecked. Do I do it on click or change?
每次选中或取消选中其中一个时,我都需要检查它。我是点击还是更改?
回答by cbrandolino
I think the easiest way is checking for this condition:
我认为最简单的方法是检查这种情况:
$('.abc:checked').length == $('.abc').length
You could do it every time a new checkbox is checked:
每次选中新复选框时,您都可以这样做:
$(".abc").change(function(){
if ($('.abc:checked').length == $('.abc').length) {
//do something
}
});
回答by Porco
$('input.abc').not(':checked').length > 0
回答by Mark Coleman
You can use change()
您可以使用 change()
$("input[type='checkbox'].abc").change(function(){
var a = $("input[type='checkbox'].abc");
if(a.length == a.filter(":checked").length){
alert('all checked');
}
});
All this will do is verify that the total number of .abc
checkboxes matches the total number of .abc:checked
.
所有这些都将验证.abc
复选框的总数是否与 的总数匹配.abc:checked
。
Code example on jsfiddle.
jsfiddle上的代码示例。
回答by manji
$('.abc[checked!=true]').length == 0
回答by Dave L.
Part 1 of your question:
您问题的第 1 部分:
var allChecked = true;
$("input.abc").each(function(index, element){
if(!element.checked){
allChecked = false;
return false;
}
});
EDIT:
编辑:
The answer (http://stackoverflow.com/questions/5541387/check-if-all-checkboxes-are-selected/5541480#5541480) above is probably better.
上面的答案(http://stackoverflow.com/questions/5541387/check-if-all-checkboxes-are-selected/5541480#5541480)可能更好。
回答by Steve Wellens
The search criteria is one of these:
搜索条件是以下之一:
input[type=checkbox].MyClass:not(:checked)
input[type=checkbox].MyClass:checked
You probably want to connect to the change event.
您可能想要连接到更改事件。
回答by Nick Cordova
Alternatively, you could have also used every():
或者,您也可以使用every():
// Cache DOM Lookup
var abc = $(".abc");
// On Click
abc.on("click",function(){
// Check if all items in list are selected
if(abc.toArray().every(areSelected)){
//do something
}
function areSelected(element, index, array){
return array[index].checked;
}
});
回答by PHPer
A class independent solution
一个类独立的解决方案
var checkBox = 'input[type="checkbox"]';
if ($(checkBox+':checked').length == $(checkBox).length) {
//Do Something
}
回答by Jaime Montoya
This is how I achieved it in my code:
这就是我在代码中实现它的方式:
if($('.citiescheckbox:checked').length == $('.citiescheckbox').length){
$('.citycontainer').hide();
}else{
$('.citycontainer').show();
}