代码之家  ›  专栏  ›  技术社区  ›  testing123

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

  •  0
  • testing123  · 技术社区  · 8 年前

    我有一些代码,检查是否至少选中了一个复选框,然后提交表单(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 回复  |  直到 8 年前
        1
  •  1
  •   Sean    8 年前

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

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

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

        2
  •  0
  •   Jay Nguyen    8 年前

    你能做到的 return

    <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">