getNumBoxesChecked Javascript Function
Back to home page | View javascript file | Comment on this codeThis function returns the number of selected checkboxes in a form. It is particularly useful for form validation, when the user is manditated to select at least x number of checkboxes.
Example
<script>
function getNumBoxesChecked(){
var total = 0;
var checkboxes_name = 'webpage[]';
var checkboxes = document.Form.elements[checkboxes_name];
var max = checkboxes.length;
//when only one in the list
if (typeof checkboxes.length=='undefined'||checkboxes=='undefined'){
var checkboxes = document.getElementById(checkboxes_name);
if(checkboxes.checked){
total = 1;
}
}
else{
for (var x = 0; x < max; x++) {
if (eval("checkboxes[" + x + "].checked") == true) {
total += 1;
}
}
}
return total;
}
</script>
Then, for PHP/ASP processing, your checkboxes should be labeled with the brackets [] so the server interprets the items as an array. For the sake of demonstration, this one is named "webpage[]".
<input type="checkbox" name="webpage[]">
Back to home page | View Javascript file