Reputation: 412
I am using the following jquery to show the selected number of checkboxes selected
$(document).ready(function(){
$('.check:button').toggle(function(){
$('input:checkbox').attr('checked','checked');
var count = $("input[type=checkbox]:checked").size();
$(this).val('uncheck all')
$("#count").text(count+ " item(s) selected");
},function(){
$('input:checkbox').removeAttr('checked');
var count = $("input[type=checkbox]:checked").size();
$(this).val('check all');
$("#count").text(count+ " item(s) selected");
})
})
here is the html
<input type="button" class="check" value="check all" />
<input type="checkbox" class="cb-element" /> Checkbox 1
<input type="checkbox" class="cb-element" /> Checkbox 2
<input type="checkbox" class="cb-element" /> Checkbox 3
<p id="count"></p>
When i check all it shows the right numbers, like 3 items selected and when i uncheck all, then it shows o items selected.
But when I remove individual selected checkbox then the count does not show up. like if i remove one, then the count will still be 3 and not the 2.
how can i achieve this?
Upvotes: 0
Views: 1174
Reputation: 17566
$( "input[type=checkbox]" ).click(function(){
$('#count').html($( "input[type=checkbox]:checked" ).length);
});
Upvotes: 0
Reputation: 57105
$("input:checkbox:checked").length;
$("input:checkbox").change(function () {
$('#count').text($("input:checkbox:checked").length);
});
Upvotes: 0
Reputation: 796
Try the :checked pseudo-class:
$("input[type=checkbox]").click(function () {
$("#count").html($("input[type=checkbox]:checked").length);
});
Upvotes: 1
Reputation: 2560
This is giving you the count:
$('input:checkbox').on('change', function(){
$('#count').html($('input:checkbox:checked').size());
});
Upvotes: 0
Reputation: 1320
var count = 0;
$('input[type=checkbox]').each(function () {
if (this.checked) {
count++;
}
});
alert(count);
Upvotes: 0
Reputation: 3844
try this code, check the api for more infomation
var countChecked = function() {
var n = $( "input:checked" ).length;
$( "p" ).text( n + (n === 1 ? " is" : " are") + " checked!" );
};
countChecked();
$( "input[type=checkbox]" ).on( "click", countChecked );
Upvotes: 1