Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a count of all checked checkboxes on a page

I want to count how many checkboxes a user has selected. For example, from a group of 10 checkboxes if he selects 5, then I want to be able to count it. Using the line:

$(":checkbox:checked")

I can select all of the checked checkboxes, is there a way to get the count of all the elements that are returned by that statement as well?

like image 480
Ali Avatar asked May 16 '09 12:05

Ali


People also ask

How can I count the number of checkboxes in PHP?

In the below script, we used foreach loop to display individual value of checked checkboxes, we have also used a counter to count number of checked checkboxes. <? php if(isset($_POST['submit'])){ if(! empty($_POST['check_list'])) { // Counting number of checked checkboxes.

How do I count a checkmark in Google Sheets?

When you use checkboxes in Google Sheets, they have default values of True if checked and False if unchecked. This is the indicator you include in the formula with the COUNTIF function. The COUNTIF function allows you to count values in cells based on criteria.


2 Answers

Use the size() method or the length property. The length property is preferred as it is faster.

Example:

var count = $("[type='checkbox']:checked").length;
like image 131
tvanfosson Avatar answered Oct 10 '22 18:10

tvanfosson


Using jQuery:

var cbs = $("input:checkbox"); //find all checkboxes
var nbCbs = cbs.length; //the number of checkboxes

var checked = $("input[@type=checkbox]:checked"); //find all checked checkboxes + radio buttons
var nbChecked = checked.length;

Using JavaScript:

var inputs = document.getElementsByTagName("input"); //or document.forms[0].elements;
var cbs = []; //will contain all checkboxes
var checked = []; //will contain all checked checkboxes
for (var i = 0; i < inputs.length; i++) {
  if (inputs[i].type == "checkbox") {
    cbs.push(inputs[i]);
    if (inputs[i].checked) {
      checked.push(inputs[i]);
    }
  }
}
var nbCbs = cbs.length; //number of checkboxes
var nbChecked = checked.length; //number of checked checkboxes

Source: How to find Checkboxes? at coderanch

like image 3
kenorb Avatar answered Oct 10 '22 19:10

kenorb