Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get number of checkboxes that are checked in Javascript

I am trying to make a javascript function (although jquery is perfectly OK) that will return a number that corresponds to the number of checkboxes checked in a form. Seems simple enough but I can't figure out a good way of doing it.

Thanks.

like image 560
DCD Avatar asked Apr 23 '10 09:04

DCD


People also ask

How do I count the number of checkboxes present in the page?

Quickest and simplest method is to find a list of the checkbox elements by the className you've provided. List<WebElement> boxes = driver. findElements(By. className("checkbox")); int numberOfBoxes = boxes.

How can I check if multiple checkboxes are checked?

Since you're providing the same name attribute to all the checkboxes (from your PHP loop), you can use the selector input[name="city[]"] to target and find them all. But to find out how many specifically are checked, you can add the :checked selector. An alternative to this is using $('input[name="city[]"]').


2 Answers

Try this:

var formobj = document.forms[0];

var counter = 0;
for (var j = 0; j < formobj.elements.length; j++)
{
    if (formobj.elements[j].type == "checkbox")
    {
        if (formobj.elements[j].checked)
        {
            counter++;
        }
    }       
}

alert('Total Checked = ' + counter);

.

With JQuery:

alert($('form input[type=checkbox]:checked').size());
like image 171
Sarfraz Avatar answered Oct 19 '22 20:10

Sarfraz


$('form :checkbox:checked').length

like image 27
Yuriy Faktorovich Avatar answered Oct 19 '22 22:10

Yuriy Faktorovich