我需要添加什么才能使它根据已选中的复选框数量进行验证?我希望用户在提交数据之前至少选择两个复选框。这是我的JavaScript代码:

    <script type="text/javascript" language="JavaScript">

function checkCheckBoxes(theForm) {
    if (
    theForm.Conservatives.checked == false &&
    theForm.Labour.checked == false &&
    theForm.LiberalDemocrats.checked == false)
    {
        alert ('Choose At Least Two Parties Who Will Be Standing For This Election');
        return false;
    } else {
        return true;
    }
}

</script>


当前的javascript代码仅验证是否选中了任何复选框,但我希望它针对两个复选框进行验证。

最佳答案

只需数一下检查的次数,看看是否小于2。

function checkCheckBoxes(theForm) {
    var cnt = 0;
    if (theForm.Conservatives.checked) ++cnt;
    if (theForm.Labour.checked) ++cnt;
    if (theForm.LiberalDemocrats.checked) ++cnt;
    if (cnt < 2) {
        alert ('Choose At Least Two Parties Who Will Be Standing For This Election');
        return false;
    } else {
        return true;
    }
}

08-19 08:59