我是jQuery的新手,我需要在同一表单的一组复选框中选中至少一个复选框。这是一个JSFiddle
HTML:
<form>
<!-- CHECKBOX GROUP NUMBER ONE -->
<h3>group one</h3>
<input type="checkbox" class="reqNow" name='part1'>
<input type="checkbox" class="reqNow" name='part1'>
<br>
<br>
<!-- CHECKBOX GROUP NUMBER TWO -->
<h3>group two</h3>
<input type="checkbox" class="reqNow" name='part2'>
<input type="checkbox" class="reqNow" name='part2'>
<!-- CHECKBOX GROUP NUMBER THREE -->
<h3>group three</h3>
<input type="checkbox" class="reqNow" name='part3'>
<input type="checkbox" class="reqNow" name='part3'>
<!-- CHECKBOX GROUP NUMBER FOUR -->
<h3>group four</h3>
<input type="checkbox" class="reqNow" name='part4'>
<input type="checkbox" class="reqNow" name='part4'>
<br>
<input type="submit">
</form>
JAVASCRIPT:
var submitOK = false;
$("form").submit(function (e) {
e.preventDefault();
var a = $(".reqNow").serializeArray();
$.each(a, function (i, b) {
if (b.value == "on") {
submitOK = true;
}
if (submitOK) {
alert("Form Sent!");
}
});
});
所以基本上我希望只有在每个组中至少选中一个复选框时才发送表单。
任何帮助表示赞赏!
答案 0 :(得分:1)
您可以检查类似于此答案JQuery Multiple Checkbox Groups Validation
$("form").submit(function (e) {
e.preventDefault();
var g1 = $('.reqNow[name=part1]:checked').length;
var g2 = $('.reqNow[name=part2]:checked').length;
var g3 = $('.reqNow[name=part3]:checked').length;
var g4 = $('.reqNow[name=part4]:checked').length;
if (g1 > 0 && g2 > 0 && g3 > 0 && g4 > 0)
alert('Form sent!');
});
请参见修改后的JSFiddle