Javascript 提交前验证,并检查是否选中每组2个复选框中的1个?

Javascript 提交前验证,并检查是否选中每组2个复选框中的1个?,javascript,Javascript,我有8个复选框,分成两组。在第一组中,我有一个标记为checkbox1的复选框和一个标记为checkbox2的复选框 我想要一个javascript代码,它允许我在表单提交中检查每个组是否至少选中了其中两个复选框中的一个 复选框是“是”和“否”值,因此每组只能选中一个 我不希望脚本只是检查您是否只选中了一个复选框,因为这意味着用户不必在另一组复选框中至少选中一个其他复选框 我使用的是IE9,所以脚本应该与IE9兼容 我该怎么做 这是我的密码: $('#form_check').on('submi

我有8个复选框,分成两组。在第一组中,我有一个标记为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,其中包含一个名为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>
此JavaScriptjQuery将检查每个“必需”组。您必须在每个组中至少选中一个复选框

$('#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');
        }
    });
});

请显示您的HTMLIf如果是/否为什么是两个复选框?用户能否同时选择是和否?如果不是,则应该只有一个复选框表示“是”,如果未选中则为“否”,或者应该是“无线电组”。@alexP下面的示例是一个更优雅的解决方案。