Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of checked checkboxes in HTML

So basically i want to count the number of checkboxes that are ticked. I get my code to the point where it counts them successfully, but I want to put in an alert that shows the number of checkboxes ticked, the code does this but doesn't show the total count, it increments the total every refresh. I just want to know how I can show a total count.

It should display the total when the radio button 'yes' is clicked.

<br />Apples <input type="checkbox" name="fruit" />Oranges <input type="checkbox" name="fruit" />Mango <input type="checkbox" name="fruit" /> <br />Yes <input type="radio" name="yesorno" id="yes" onchange="checkboxes()" 
function checkboxes(){     var inputElems = document.getElementsByTagName("input"),     count = 0;     for (var i=0; i<inputElems.length; i++) {     if (inputElems[i].type === "checkbox" && inputElems[i].checked === true){         count++;         alert(count);     } }} 
like image 674
roro Avatar asked Apr 08 '14 13:04

roro


People also ask

How many checkboxes we can check at a time?

So user can select as many checkboxes they want but sum can't exceed 10.

What is the value of a checked checkbox in HTML?

The Input Checkbox defaultChecked property in HTML is used to return the default value of checked attribute. It has a boolean value which returns true if the checkbox is checked by default, otherwise returns false.


1 Answers

This should do the trick:

alert(document.querySelectorAll('input[type="checkbox"]:checked').length);

like image 150
Marlon Bernardes Avatar answered Sep 21 '22 04:09

Marlon Bernardes