Biker John
Biker John

Reputation: 2711

jQuery : Counting checked checkboxes - wrong count

I have a code which counts the checked checkboxes. It works fine when selecting, but the count breaks (adds +1 to the count) when i deselect some of the already selected checkboxes.

HTML:

<div>Number of checkboxes checked: <span id='chck'>0</span></div>
<table>
    <tr><td><input type='checkbox' /></td></tr> 
    <tr><td><input type='checkbox' /></td></tr> 
    <tr><td><input type='checkbox' /></td></tr> 
    <tr><td><input type='checkbox' /></td></tr> 
    <tr><td><input type='checkbox' /></td></tr> 
    <tr><td><input type='checkbox' /></td></tr> 
    <tr><td><input type='checkbox' /></td></tr>    
</table>

JS:

$('tr :checkbox').change(function(){

    $('#chck').text($(this).add(':checked').length);

});

FIDDLE: http://jsfiddle.net/kAsxj/

Upvotes: 1

Views: 543

Answers (4)

Venkata Krishna
Venkata Krishna

Reputation: 15112

DEMO

   $('tr :checkbox').change(function(){
        $('#chck').text($(':checkbox:checked').length);
    });

Upvotes: 1

David Thomas
David Thomas

Reputation: 253318

When you check or un-check a check-box the count doesn't automatically increase, so you'd need:

$('input[type="checkbox"]').change(function(){
    $('#chck').text($('input[type="checkbox"]:checked').length);
}).change();

JS Fiddle demo.

Upvotes: 1

Chris
Chris

Reputation: 28064

http://jsfiddle.net/kAsxj/3/

Not sure why you're using $(this).add(':checked') when simply $(':checked') will suffice.

Upvotes: 1

Anton
Anton

Reputation: 32581

Try this

$('#chck').text($('input[type="checkbox"]:checked').length);
    //gets all input checkboxes

or for the specific table with inputs you can do this

$('#chck').text($(this).closest('table').find(':checked').length);
//gets all input checkboxes within the table

DEMO

Upvotes: 1

Related Questions