18

I want to count how many checkboxes on my page are selected using jQuery. I've written the following code:

      var numberOfCheckboxesSelected = 0;
      $(':checkbox').each(function(checkbox) {
          if (checkbox.attr('checked'))
              numberOfCheckboxesSelected++;
      });

However, my code errors out with the message "Object doesn't support this property or method" on the third line.

How do I count how many checkboxes are selected on my page?

5 Answers 5

46

jQuery supports the :checked pseudo-selector.

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

This will work for radio buttons as well as checkboxes. If you just want checkboxes, but also have radio buttons on the page:

var n = $("input:checkbox:checked").length;
1
  • 4
    You should do input:checkbox instead of just :checkbox so jQuery doesn't look at all elements on the page.
    – user113716
    Commented Jan 25, 2011 at 16:27
5

Try this(to avoid counting any selected radio buttons):

var numberOfCheckboxesSelected = $('input[type=checkbox]:checked').length; 
3

The first argument passed to the callback in each is the index, not the element. You should use this or a second argument:

$(':checkbox').each(function(idx, checkbox) {
      if (checkbox.attr('checked'))
          numberOfCheckboxesSelected++;
});

Moreover, the easier way to do this is to select only the checked elements with the :checked selector and then check the selection's length property:

var numberOfCheckboxesSelected = $('input:checkbox:checked').length;
1
$("input:checked").length

this will return the count of checked checkboxes.

0

$('#myDIV').on('change', 'input[type="checkbox"]', function(){
  var $checkbox = $('#myDIV').find('input[type="checkbox"]')
    $count = 0,
    $counter = $('#myDIV').find('.counter');
  $checkbox.each(function() {
    if ($(this).is(':checked')) {
      $count++;
    }
  });
  $counter.text($count);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myDIV">
  <label>
    <input type="checkbox"> label
  </label>
  <br>
  <label>
    <input type="checkbox"> label
  </label>
  <br>
  <label>
    <input type="checkbox"> label
  </label>
  <br>
  <label>
    <input type="checkbox"> label
  </label>
  <br>
  <span class="counter">0</span>
</div>

1
  • 1
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Jul 28, 2023 at 23:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.