Given the code on the page?

<div class="block"> <input type="checkbox" value="1" name="one"> <input type="checkbox" value="2" name="two"> <input type="checkbox" value="3" name="three"> <input type="checkbox" value="4" name="four"> </div> 

How can I make calculations and get the sum of value (answer 10) and know how many checkboxes at the same time selected the whole (in this case 4). The name of the field is not important, you can make all the name = "box []"

    2 answers 2

    All checkboxes make one name = "cname"

     var sum = 0; var elements = tableElem.getElementsByName('cname'); for (var i = 0; i < elements.length; i++) { var input = elements[i]; sum = sum + input.value; alert( input.value + ': ' + input.checked ); } 

    elements.length - number of checkboxes

    sum - sum

    • Your code is not working. - Developer Developer

    Another option, without specifying the name and other attributes, which in my opinion is more correct , returns the sum by a number .

     var summ = 0; for (var i = 0; i<document.getElementsByTagName ("input").length; i++) { if (document.getElementsByTagName ("input")[i].type == "checkbox") { var num = parseInt (document.getElementsByTagName ("input")[i].value) summ += num; if (i==document.getElementsByTagName ("input").length-1) { alert (summ); }; }; };