Since all the other answers are based on jquery, I offer a clean JavaScript solution. Assuming the following view:
<form id="myform"> <input type="checkbox" value="username1" name="check[0]" /><br/> <input type="checkbox" value="userusername2" name="check[1]" /><br/> <input type="checkbox" value="userusername3" name="check[2]" /><br/> </form>
You can calculate the number of checkbox elements with the following logic:
<script type="text/javascript"> var myform = document.getElementById('myform'); var inputTags = myform.getElementsByTagName('input'); var checkboxCount = 0; for (var i=0, length = inputTags.length; i<length; i++) { if (inputTags[i].type == 'checkbox') { checkboxCount++; } } alert(checkboxCount); </script>
BTW: As others have noted, the id attribute in any HTML tag must be unique in the document. I omitted your id="1" attributes in my HTML example above.
Update:
If you just want to read all the checkbox elements throughout the page without using the containing form element, this should work:
<script type="text/javascript"> var inputTags = document.getElementsByTagName('input'); var checkboxCount = 0; for (var i=0, length = inputTags.length; i<length; i++) { if (inputTags[i].type == 'checkbox') { checkboxCount++; } } alert(checkboxCount); </script>
Asaph source share