1

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

1
  • .category1 :checked means, select all selected elements that are descendants of .category1 elements. Instead you want .category1:checked which means "select all .category1 elements which are also selected. Commented Jan 30, 2014 at 7:06

5 Answers 5

3

Use length property instead of size() method

Check the following code..

$('.category1:checked').length;

Check the following image.. enter image description here

And check the JSFIDDLE

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

3 Comments

Why should .length work instead of .size()? They are both the same.
(of course .length is preferred and .size is deprecated, but that doesn't explain why .size() doesn't work. Hence the problem is likely something else.)
@Rahul: .size() works, your selector is wrong. It's correct in this answer, but not explained. See my comment to your question.
3

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.

Live Demo

var category1Count = $('.category1:checked').length;

Comments

2

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')

demo

Comments

0

Try

var category1Count = $("input:checkbox:checked").length;

Comments

0
 $(document).ready(function(){
      $(".category1").click(function(){
          console.log($(":checkbox").filter(":checked").size());              
      });
 });

Fiddle Demo

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.