[英]validate before submit and check if 1 of 2 check boxes per group is checked?
我有8个复选框,分为2个组。在第一组中,我有一个标记为checkbox1的复选框和一个标记为checkbox2的复选框。
我想要一个JavaScript代码,使我能够检查表单提交是否已为每个组选中了至少两个复选框中的一个。
复选框为是,没有值,因此每个组只能选中一个。
我不希望脚本仅检查您是否仅选中了一个复选框,因为这将意味着用户不必检查另一组复选框中的至少一个其他复选框。
我正在使用IE9,因此该脚本应与IE9兼容。
我怎样才能做到这一点 ?
这是我的代码:
$('#form_check').on('submit', function (e) {
if ($("input[id=checkbox1]:checked").length === 0) {
if ($("input[id=checkbox2]:checked").length === 1) {
}else{
if ($("input[id=checkbox2]:checked").length === 0) {
if ($("input[id=checkbox1]:checked").length === 1) {
e.preventDefault();
alert('no way you submit it without checking a box');
return false;
}
});
这可能就是您想要的,如果没有让我知道,我会尝试将其整理得更好一些。
首先,让我们整理一下代码。 您似乎有大量的if语句,并且大多数语句都没有终止。
其次,我给您的印象是,您想检查是否按下了其中一个,并且至少按下了一个,但不是两者都按下。
$('#form_check').on('submit', function (e) {
if ($("input[id=checkbox1]:checked").length === 0 && $("input[id=checkbox2]:checked").length === 0) { // if neither is selected && means and
e.preventDefault();
alert('nothing selected');
return false;
}
else if (($("input[id=checkbox1]:checked").length === 1 && $("input[id=checkbox2]:checked").length === 0) || ($("input[id=checkbox2]:checked").length === 1 && $("input[id=checkbox1]:checked").length === 0)) { //if a is selected and b is not OR (||) b is selected but not a
e.preventDefault();
alert('congrats one or other of the check boxes is selected');
return false;
}
else{ //otherwise you must have selected both
e.preventDefault();
alert("you've managed to select BOTH yes and no");
return false;
}
});
您可以使用DIV嵌入每个复选框组,该DIV的类名为“ required”
<form id="form_check">
<div class="required">
<input type="checkbox" id="checkbox1" />Test 1
<input type="checkbox" id="checkbox2" />Test 2
</div>
<div class="required">
<input type="checkbox" id="checkbox3" />Test 3
<input type="checkbox" id="checkbox4" />Test 4
</div>
<input type="submit" value="Submit" />
</form>
此JavaScript(jQuery)将检查每个“必需”组。 您必须至少选中每个组中的一个复选框。
$('#form_check').on('submit', function (e) {
e.preventDefault();
$('.required').each(function () {
if ( $(this).find('input:checked').length <= 0 ) {
alert('no way you submit it without checking a box');
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.