Restrict number of selected checkboxes in html

This code will restrict html multi select input to given number.

document.addEventListener( "click", function( event ) {
    if ( event.target.matches( '.input-checkbox' ) ) {
        var inputCheckboxes = document.querySelectorAll( '.input-checkbox[type="checkbox"]:checked' );
        if( inputCheckboxes.length > 3 ) {
            event.preventDefault();
            alert( 'You cannot select more than 3 categories for a post.' );
        }
    }
} );

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *