使用必需的复选框验证来防止表单提交

Using required checkbox validation to prevent form submission

我有一些代码可以检查是否至少选中了一个复选框,然后提交表单 (MailChimp)。我的问题是,如果发现没有选中任何复选框,我不知道如何停止 MailChimp 提交。现在它显示警报,然后无论如何都提交表单......没什么帮助。

<form onsubmit="valthis()" action="//mailchimp form" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

// form html

        <script>function valthis() {
var checkBoxes = document.getElementsByClassName( 'myCheckBox' );
var isChecked = false;
    for (var i = 0; i < checkBoxes.length; i++) {
        if ( checkBoxes[i].checked ) {
            isChecked = true;
        };
    };
    if ( isChecked ) {
        alert( 'At least one checkbox is NOT checked!' );
        }   
}</script>

<input type="submit" value="Subscribe to notifications" name="subscribe" id="mc-embedded-subscribe" class="button">

你可以在处理数据时return你的JS函数的值:

<form onsubmit="return valthis()" action="//mailchimp form" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

<script>
function valthis() {
    var checkBoxes = document.getElementsByClassName( 'myCheckBox' );
    var isChecked = false;

    for (var i = 0; i < checkBoxes.length; i++) {
        if ( checkBoxes[i].checked ) {
            isChecked = true;
            break; //don't need to continue the loop once a checkbox was found
        }
    }

    if ( !isChecked ) {
        alert( 'At least one checkbox is NOT checked!' );
        return false;
    }

    return true;
}
</script>

<input type="submit" value="Subscribe to notifications" name="subscribe" id="mc-embedded-subscribe" class="button">

您需要在提交时向表单添加事件

document.getElementsByName("subscribe").onsubmit(function(event) {
    if(!isChecked) { //If not checked
        event.preventDefault(); // stops the form submitting
    }
});

如果没有复选框被选中 preventDefault。这会阻止表单提交