Reputation: 67
I'm trying to count the number of checkboxes that have been checked. But, the count remains 0 even though I click. Here is my code.
<div>
<input type="checkbox" class="category1"></input>
<input type="checkbox" class="category1"></input>
<input type="checkbox" class="category1"></input>
<input type="checkbox" class="category1"></input>
</div>
and my JS code is..
<script type="text/javascript">
$(document).ready(function(){
$(".category1").click(function(){
var category1Count = $('.category1 :checked').size();
console.log(category1Count);
});
});
</script>
There must be a simple mistake. Not able to find out. Where am I going wrong? Thanks in advance
Upvotes: 1
Views: 2459
Reputation: 85545
size() and length both works but in the OP code he was just placing a space which causing not to work.
$('.category1 :checked')
should be this: $('.category1:checked')
Upvotes: 2
Reputation: 148110
Use length
to get the count of elements. You also do not need space between .category1
and :checked
The .size() method is deprecated as of jQuery 1.8. Use the .length property instead.
The .size() method is functionally equivalent to the .length property; however, the .length property is preferred because it does not have the overhead of a function call. Reference.
var category1Count = $('.category1:checked').length;
Upvotes: 3
Reputation: 5813
Use length property instead of size() method
Check the following code..
$('.category1:checked').length;
Check the following image..
And check the JSFIDDLE
Upvotes: 3
Reputation: 2827
$(document).ready(function(){
$(".category1").click(function(){
console.log($(":checkbox").filter(":checked").size());
});
});
Upvotes: 0