getNumBoxesChecked Javascript Function

Back to home page | View javascript file | Comment on this code

This 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

Webpage Select
www.seandempsey.com
www.downwiththeloads.com
www.gasguzzle.com

<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



Your Rating      Overall Rating   

Comment on this Code

Your Name
Comment

Recent Comments

"next message from me: i`ve experimented with this code and after some changes in makeAjaxEditor() your work gives me great help in solving an AJAX-problem....

Thank you very much! Great done..
" - Posted by wolga wibri on Monday Apr 21st, 2008 at 10:17am

"Great stuff, you helepd me out so much!" - Posted by Lyza on Wednesday Jul 13th, 2011 at 10:23pm

"Thanks for sharing. What a paluesre to read!" - Posted by Kumbang on Tuesday Oct 16th, 2012 at 6:37pm