Rahul
Rahul

Reputation: 67

Count selected checkboxes using jquery.

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

Answers (5)

Bhojendra Rauniyar
Bhojendra Rauniyar

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

demo

Upvotes: 2

Adil
Adil

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.

Live Demo

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

Upvotes: 3

Hasib Tarafder
Hasib Tarafder

Reputation: 5813

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

Upvotes: 3

NiiL
NiiL

Reputation: 2827

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

Fiddle Demo

Upvotes: 0

Sid M
Sid M

Reputation: 4354

Try

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

Upvotes: 0

Related Questions