views:

300

answers:

5

I am trying to make a javascript function (although jquery is perfectly OK) that will return a number that corresponds to the number of checkboxes checked in a form. Seems simple enough but I can't figure out a good way of doing it.

Thanks.

+1  A: 

Try

$(":checkbox").filter(":checked").size()
kgiannakakis
@Yuriy Faktorovich: Just for illustration. I have now removed it@Sarfraz: You are right. I've corrected it
kgiannakakis
+8  A: 

Try this:

var formobj = document.forms[0];

var counter = 0;
for (var j = 0; j < formobj.elements.length; j++)
{
    if (formobj.elements[j].type == "checkbox")
    {
        if (formobj.elements[j].checked)
        {
            counter++;
        }
    }       
}

alert('Total Checked = ' + counter);

.

With JQuery:

alert($('form input[type=checkbox]:checked').size());
Sarfraz
Just for clarification - the standard JS code will not pick up input elements that are not inside a form. The jQuery line will.
danp
@danp: yes now both ways will select all checkboxes from a form.
Sarfraz
+2  A: 
var chk = $('form').find('input[type=checkbox]:checked').length

Kind Regards

--Andy

jAndy
+3  A: 

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

Yuriy Faktorovich
+2  A: 
 var checkBoxs = $('#myForm').children('input[type="checkbox"]:checked');
 alert(checkBoxs.length);
pashaweb