OM The Eternity OM The Eternity - 3 months ago 8
Javascript Question

How to validate for checkbox selection if all checkbox have same name?

Hi All
I have a group of check box having same name so as to get the array of single variable when it is posted on serverside for exampleL

<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">


I need a javascript validation to check whether any checkbox is selected or not?

Thanks and Regards

NOTE: I need javascript validation

Answer
<form name="myform" method="POST" action="" onsubmit="return checkTheBox();">
  <input type="checkbox" name="midlevelusers[]" value="1" /> 1 &nbsp;&nbsp;
  <input type="checkbox" name="midlevelusers[]" value="2" /> 2 &nbsp;&nbsp;
  <input type="checkbox" name="midlevelusers[]" value="3" /> 3 &nbsp;&nbsp;
  <input type="checkbox" name="midlevelusers[]" value="4" /> 4 &nbsp;&nbsp;
  <input type="checkbox" name="midlevelusers[]" value="5" /> 5 &nbsp;&nbsp;
  <input type="submit" value="Submit Form" />
</form>

<script type="text/javascript">
  function checkTheBox() {
    var flag = 0;
    for (var i = 0; i< 5; i++) {
      if(document.myform["midlevelusers[]"][i].checked){
        flag ++;
      }
    }
    if (flag != 1) {
      alert ("You must check one and only one checkbox!");
      return false;
    }
    return true;
  }
</script>