开发者

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

开发者 https://www.devze.com 2022-12-14 15:04 出处:网络
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开发者_JAVA技巧 that the user check exactly 2 checkboxes.if( $(\'inp

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开发者_JAVA技巧 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;
0

精彩评论

暂无评论...
验证码 换一张
取 消