Categories
Coding

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.' );
        }
    }
} );

By Abhineet Mittal

Abhineet is IIM Alumnus and Founder of popular Digital Publishing Platform, Sahityapedia. He is a technology enthusiast by hobby & an avid reader.

Leave a Reply

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