JQuery 检查复选框是否被选中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8611887/
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
JQuery Check if Checkbox is Checked
提问by user582065
I'd like to figure out how to write something like the following to validate single check boxes. There could be just one on the form or many separate ones. The example below doesn't work.
我想弄清楚如何编写如下内容来验证单个复选框。表格上可能只有一个,也可能有许多单独的。下面的例子不起作用。
Thank you!
谢谢!
// -----------------------------------------------
// CHECK SINGLE CHECKBOX
// -----------------------------------------------
$('.mcCbxRequired').each(function() {
var mcCbxCheck = $(this);
if(mcCbxCheck.is(':checked')) {
alert('checked');
// do something here ...
}
else{
alert('not checked');
return false;
}
});
回答by Devin Burke
A couple things:
一些事情:
Each applicable checkbox must have the
mcCbxRequired
class. If neither alert shows, the problem must be because your checkbox does not have this class.You are
return
ingfalse
in both cases. That doesn't really make sense with validation, so you should change the relevant part of your code to this:
每个适用的复选框都必须具有
mcCbxRequired
类。如果两个警报都没有显示,则问题一定是因为您的复选框没有此类。你在这两种情况下都是
return
ingfalse
。这对验证没有意义,因此您应该将代码的相关部分更改为:
Code:
代码:
if(mcCbxCheck.is(':checked')) {
alert('checked');
return true;
}
回答by Varun Goel
You can use:
您可以使用:
$('input[type=checkbox]:checked').each(function()
{
var checkedBox = $(this);
// Do whatever you want
});
Also, JQuery selectors by Class are slower than by id/by type.
此外,JQuery 选择器按类比按 id/按类型慢。