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?
Use the size() method or the length property. The length property is preferred as it is faster.
Example:
var count = $("[type='checkbox']:checked").length;
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