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
  • What have you tried? Did you try checking the docs? api.jquery.com/category/selectors Commented May 1, 2012 at 18:23
  • Ahh was just missing the colon between input and checked Commented May 1, 2012 at 18:25

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;
Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

1

You could try this:

$('#form input:checkbox:checked').length;

Comments

-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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.