Adnan
Adnan

Reputation: 2967

Counting checked checkboxes

I'm having a problem counting checked checkboxes in jQuery that runs counter to every example I could find. The following code works:

var checked_boxes = $('input:checkbox:checked').length // Returns 1 or 2 etc.

However, I would like to modify that to count the number of checkboxes of a particular class, say my_class. I have tried the following:

var checked_boxes = $('input.my_class:checked').length // Always 0
var checked_boxes = $('input.my_class:checkbox:checked').length // Always 0
var checked_boxes = $('input[type=checkbox].my_class:checked').length // 0 also

Same with several other syntaxes/permutations I tried.

For some background, these checkboxes are in a table in a td and essentially look like so:

<input type="checkbox" id="cb1" class="some_class_for_display_style my_class" value="1" />Blah

Any idea what I'm missing here?

EDIT:

Found the problem: It was the mis-placed class. I added an answer to that effect.

Upvotes: 6

Views: 23431

Answers (4)

westo
westo

Reputation: 575

Remove the $ sign in the selector.

$('input.my_class:checked').length - Count of checkboxes which are checked

$('input.my_class').length - Count of all checkboxes with class my_class

Upvotes: 18

Adnan
Adnan

Reputation: 2967

Fastest Rubber Duck answer ever!!

Right after posting here I went back to looking at my code and realized to my horror that I had applied the class to the td not the check_box_tag (I'm using Rails).. moved the class to the check_box_tag and it seems to be working now.

Thanks everyone!

Upvotes: 1

Tats_innit
Tats_innit

Reputation: 34107

Is this what you are looking for:

It will be good if you can provide a working JSFiddle but hope link below will help you.

Example: (You are looking mix of these 2)

http://jsfiddle.net/mtYtW/30/ AND http://jsfiddle.net/karim79/LUtJF/1/

Few good answers here:

Jquery how to count checked and disable checkboxes

Hope it helps, Cheers

Upvotes: 1

Jon Egeland
Jon Egeland

Reputation: 12613

If $input is a PHP variable, you need to escape the JS string to use the variable:

var checked_boxes = $('<?php echo $input ?>'.my_class:checked).length;

If it is a JS variable, same thing:

var checked_boxes = $('input.<?php echo $my_class; ?>:checked').length;

And if it is not a variable, you just need to remove the initial $ from the selector:

var checked_boxes = $('input.my_class:checked').length;

Upvotes: 0

Related Questions