JavaScript to Check if Checkbox Checked

On this page we show how to use JavaScript to check whether a checkbox has been checked before submitting a form. If this required checkbox has not been checked when the user attempts to submit the form, an error message will be displayed and submission of the form will be prevented.

The following form demonstrates:

Demo: Inspect Required Checkbox

Please check the box to signify agreement with our terms.

The JavaScript displayed here shows how this can be accomplished:

// assign function to onsubmit property of form
document.getElementById('demoForm').onsubmit = function() {
    // get reference to required checkbox
    var terms = this.elements['terms'];
    
    if ( !terms.checked ) { // if it's not checked
        // display error info (generally not an alert these days)
        alert( 'Please signify your agreement with our terms.' );
        return false; // don't submit
    }
    return true; // submit
};

We get a reference to the form and assign a function to its onsubmit property. Then inside the function we get a reference to the checkbox and inspect its checked property to see whether it has been checked. If not, an error message is displayed and we return false to prevent submission of the form. Otherwise we return true to allow the form to be submitted.

More Required Checkbox Examples

Each of the examples in the tutorial on JavaScript Event Handling demonstrates with a required checkbox. The tutorial presents four ways to attach event handlers, and shows how the method chosen influences the means of accessing the form, its elements, and the event object within the handler function.