views:

265

answers:

3

Hi, 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.

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

Alternatively, use

$('myForm :checkbox:checked').length
Stefan Kendall
can I specify a class for the checkbox?
Pennywise83
I've solved: $('input[type="checkbox"][name=checkb_name]:checked')
Pennywise83
A: 
var amountOfSelectedCheckboxes = $('input[type=checkbox]:checked').length;
pixeline
+1  A: 

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);
    }
lincolnk
Give a man a bandaid, and he may be able to heal a wound. Give a man a doctor with full medical supplies, and the wound becomes an implementation detail. Not all cuts are solvable with bandaids.
Stefan Kendall