1

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/

3
  • add is for adding an element. Commented Oct 7, 2013 at 15:01
  • @MatthewRiches Yes i can see that now. I thought it was a function to add selector to the existing $this Commented Oct 7, 2013 at 15:03
  • 2
    It is to add a selector to the existing $this. But you don't check to see if $this is checked, originally. That's why you're off by one when you are deselecting. Commented Oct 7, 2013 at 15:04

4 Answers 4

1

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

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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.

Comments

1

DEMO

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

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.