3

I have one form on a page and within that form there will be a check box for every row in the table. I need to count the number of rows that have a checked row, but I am having trouble even selecting that from jQuery.

Here is what my code looks like for a checkbox:

<input type="checkbox" id="onHomePage_56" name="onHomePage" 
    value="56" checked="checked">

An unchecked box doesn't have checked="checked".

2

4 Answers 4

7
var q = $('form#id-of-form').find('input:checked').length;

http://api.jquery.com/checked-selector/

If there are checkboxes in the form you don't want counted, then add a class to the ones you do want counted and select those instead:

var q = $('form#id-of-form').find('input.count-these:checked').length;
2

jQuery provides special selectors for this:

$('input:checked').length

More specifically:

var num = $('#myform input:checkbox:checked').length;

I added the jQuery :checkbox selector because :checked applies to radio buttons as well. Technically, :checkbox is slower than [type=checkbox] in modern browsers, but they do the same thing:

var num = $('#myform input[type=checkbox]:checked').length;
0
1

You could try this:

$('#form input:checkbox:checked').length;
-1
$('#myForm table tr td input:checked')​.size();​

DEMO.

Update: Better to filter type because you could have checked radio buttons too

$('#myForm table tr td input[type="checkbox"]:checked').size();

Demo with checked radio buttons

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.