Reputation: 2711
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
Reputation: 15112
$('tr :checkbox').change(function(){
$('#chck').text($(':checkbox:checked').length);
});
Upvotes: 1
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();
Upvotes: 1
Reputation: 28064
Not sure why you're using $(this).add(':checked')
when simply $(':checked')
will suffice.
Upvotes: 1
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
Upvotes: 1