Search code examples
javascriptvalidationcheckboxrequire

Using required checkbox validation to prevent form submission


I've got some code that checks if at least one checkbox is selected and then submits the form (MailChimp). My problem is I don't know how to stop the MailChimp submission if it catches that no checkboxes are selected. Right now it shows the alert and then submits the form anyway ... little help.

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

Solution

  • You can do return the value of your JS function when processing data:

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