JQuery多个复选框组验证 [英] JQuery Multiple Checkbox Groups Validation
问题描述
如何使用JQuery验证Checkbox组?我需要确保在每个组中至少选择一个复选框。我想使用一个类来标识组,所以,html会是这样:
How can I validate Checkbox groups with JQuery? I need to make sure that in each group at least one checkbox is selected. I'd like to use a class to identify the groups, so, the html would look like this:
<!-- checkbox group -->
<fieldset class="CbxGroup">
<legend>Checkbox Group (required)</legend>
<label><input type="checkbox" name="cbxGroup1[]" value="one" id="cbxGroup1_0">One </label>
<br>
<label><input type="checkbox" name="cbxGroup1[]" value="two" id="cbxGroup1_1">Two </label>
<br>
<label><input type="checkbox" name="cbxGroup1[]" value="three" id="cbxGroup1_2">Three</label>
<br>
<label><input type="checkbox" name="cbxGroup1[]" value="four" id="cbxGroup1_3">Four </label>
<br>
<label><input type="checkbox" name="cbxGroup1[]" value="five" id="cbxGroup1_4">Five </label>
<br>
</fieldset>
因为复选框没有像select list / menu这样的包装元素,所以我不知道如何拉这个。对于单个复选框,我可以做如下,但它不适用于复选框组:
Because checkboxes don't have a wrapper element like the select list/menu, I don't know how to pull this off. For single checkboxes I can do something like the following but it does not work for checkbox groups:
谢谢!
$('.CbxSingle').each(function() {
var CbxCheck = $(this);
if(!CbxCheck.is(':checked')) {
// do something
}
else{
// do something else
}
});
我想要类似以下内容,分别验证每个组:
I'd like something like the following that would validate each group separately:
$('.CbxGroup').each(function() {
if ($('input[type=checkbox]:checked').length == 0) {
alert('not selected!');
}
else{
alert('selected!');
}
});
推荐答案
Perhaps something like this might work:
if($(".CbxSingle input[type=checkbox]:checked").length != 0){
// Run success code
}else{
// Run failure code
}
实际上,在jQuery文档网站上有一个非常相似的参考:checked选择器: http:/ /api.jquery.com/checked-selector/
There is actually a very similar reference on the jQuery documentation website for the :checked selector: http://api.jquery.com/checked-selector/
希望有所帮助!
这篇关于JQuery多个复选框组验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!