Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
2
rated 0 times [  8] [ 6]  / answers: 1 / hits: 17810  / 13 Years ago, mon, april 25, 2011, 12:00:00

I have number of check boxes that gets generated dynamically. So i do not know how many check boxes gets generated each time. I need to have some JavaScript ways to count the total numbers of check boxes in a form.



 <input type=checkbox value=username1 name=check[0] id=1 /><br/>
<input type=checkbox value=userusername2 name=check[1] id=1 /><br/>
<input type=checkbox value=userusername3 name=check[2] id=1 /><br/>


I can not change the name of the check boxes as i need to send the values to serverside PHP script as an array.


More From » php

 Answers
9

Since all other answers are jquery based, I'll offer a pure javascript solution. Assuming the following form:



<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 could compute 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 should be unique within the document. I've omitted your id=1 attributes in my sample HTML above.



Update:



If you simply want to count all checkbox elements on the entire page without using a 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>

[#92580] Friday, April 22, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bobbidayanam

Total Points: 82
Total Questions: 99
Total Answers: 96

Location: Venezuela
Member since Sat, Apr 24, 2021
3 Years ago
bobbidayanam questions
Sat, Mar 21, 20, 00:00, 4 Years ago
Mon, Dec 24, 18, 00:00, 6 Years ago
Fri, Nov 16, 18, 00:00, 6 Years ago
;