开发者

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开发者_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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜