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>
<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>
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
<script language = "javascript">
function chkbutton()
{
document.form1.thebutton.d isabled = true;
for(var i=0; i< document.form1.elements['c hk[]'].len gth;i++)
{
if(document.form1.elements ['chk[]'][ i].checked )
{
document.form1.thebutton.d isabled = 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>
function chkbutton()
{
document.form1.thebutton.d
for(var i=0; i< document.form1.elements['c
{
if(document.form1.elements
{
document.form1.thebutton.d
}
}
}
</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>
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>