简体   繁体   中英

Form check with JS: select at least one checkbox and max 2 checkboxes

is there a way to validate a form through JS and check how many checkboxes are selected? I have a list with 15 checkboxes and I want that the user check exactly 2 checkboxes.

if( $('input[type="checkbox"]:checked').length == 2 )
{
   //good
}
else
{
   //bad
}

Alternatively, use

$('myForm :checkbox:checked').length

if you don't want to rely on jquery

    function exactly2() {
        var inputs = document.getElementsByTagName("input");
        var count = 0;

        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].type == "checkbox" && inputs[i].checked) {
                count++;
            }
        }

        return (count == 2);
    }
var amountOfSelectedCheckboxes = $('input[type=checkbox]:checked').length;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM