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); } }}
So user can select as many checkboxes they want but sum can't exceed 10.
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.
This should do the trick:
alert(document.querySelectorAll('input[type="checkbox"]:checked').length);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With