Link to home
Start Free TrialLog in
Avatar of soBC
soBC

asked on

Cycle through checkboxes on a form and determine if at least one has been checked

I have a form with 3 checkboxes.  I need the button to be disabled until the user clicks one of the boxes, at which point it will become enabled.  If the user clicks a checkbox, and then clicks again (un-checking it), i need to cycle through all the checkbxes to see whether or not one is still checked in order to set the correct state of the buttons.  What I cant figure out is the javacript syntax to check the value of all the checkboxes in a form after an onClick event, or something similar?

<form name="form1">

<input type="checkbox" value="1">1
<input type="checkbox" value="2">2
<input type="checkbox" value="3">3

<input type="button" disabled value="Go">
</form>
Avatar of minichicken
minichicken

<script language = "javascript">
function chkbutton()
{
      if (form1.chk1.checked == true || form1.chk2.checked == true || form1.chk3.checked == true)
      {
            form1.thebutton.disabled = false;            
      }
      else
      {
            form1.thebutton.disabled = true;
      }
}
</script>
<form name="form1">

<input name ="chk1" type="checkbox" value="1" onclick ="chkbutton();">1
<input name ="chk2" type="checkbox" value="2" onclick ="chkbutton();">2
<input name ="chk3" type="checkbox" value="3" onclick ="chkbutton();">3

<input name ="thebutton" type="button" disabled value="Go">
</form>
Avatar of soBC

ASKER

Ah...i have one more condition actually.  The number of checkboxes may not always be 3.  I need to account for that variation.  Thanks for the sample though.  It'll work fine statically, but Im not sure how I'd modify it to handle dynamically generated lists of checkboxes...
ASKER CERTIFIED SOLUTION
Avatar of nan1217
nan1217

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
<script language = "javascript">
function chkbutton()
{
      document.form1.thebutton.disabled = true;
      
      for(var i=0; i< document.form1.elements['chk[]'].length;i++)
      {
            if(document.form1.elements['chk[]'][i].checked)
            {
                  document.form1.thebutton.disabled = false;
            }
      }
}



</script>
<form name="form1">

<input name ="chk[]" type="checkbox" value="1" onclick ="chkbutton();">1
<input name ="chk[]" type="checkbox" value="2" onclick ="chkbutton();">2
<input name ="chk[]" type="checkbox" value="3" onclick ="chkbutton();">3

<input name ="thebutton" type="button" disabled value="Go">
</form>