Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I count how many checkboxes are selected on a page with jQuery

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?

like image 801
Vivian River Avatar asked Jan 25 '11 16:01

Vivian River


People also ask

How do you count the number of check boxes in the page?

We can count the total number of checkboxes in a page in Selenium with the help of find_elements method. While working on any checkboxes, we will always find an attribute type in the html code and its value should be checkbox.

How can I check if multiple checkboxes are checked in jQuery?

Using jQuery is(':checked')change(function(ev) { if ( $(this).is(':checked') ) console. log('checked'); else console. log('not checked'); }); If multiple checkboxes match the jQuery selector, this method can be used to check if at least one is checked.


1 Answers

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;
like image 79
Stephen Avatar answered Oct 24 '22 01:10

Stephen