DCD
DCD

Reputation: 1290

Get number of checkboxes that are checked in Javascript

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.

Upvotes: 9

Views: 15457

Answers (6)

Affan
Affan

Reputation: 31

vary long way

you have to give the class name to checkbox and do

var chkLength = $('input.className:checked').length;

alert(chkLength);

this will gove all checked checkBoxes from list of checkbox

Upvotes: 0

jAndy
jAndy

Reputation: 235982

var chk = $('form').find('input[type=checkbox]:checked').length

Upvotes: 2

Sarfraz
Sarfraz

Reputation: 382686

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());

Upvotes: 16

pashaweb
pashaweb

Reputation: 82

 var checkBoxs = $('#myForm').children('input[type="checkbox"]:checked');
 alert(checkBoxs.length);

Upvotes: 4

kgiannakakis
kgiannakakis

Reputation: 104168

Try

$(":checkbox").filter(":checked").size()

Upvotes: 1

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68667

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

Upvotes: 4

Related Questions