使用所需的复选框验证来阻止表单提交

时间:2017-08-08 13:55:44

标签: javascript validation checkbox require

我有一些代码检查是否至少选中了一个复选框,然后提交表单(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">

2 个答案:

答案 0 :(得分:1)

您需要在提交

的表单中添加一个事件
document.getElementsByName("subscribe").onsubmit(function(event) {
    if(!isChecked) { //If not checked
        event.preventDefault(); // stops the form submitting
    }
});

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

答案 1 :(得分:0)

处理数据时,您可以{JS}执行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">