Click to See Complete Forum and Search --> : Checkbox Validation


jskeens
01-02-2003, 09:31 AM
I am working on a form for my Web page and I am trying to do some validation for checkboxes. I want to send an alert if no checkboxes are selected after the user clicks the submit button. I have written a piece of code but it doesn't seem to be working. I would take all of the advice I can get. Here is what I have written so far.

function checkCheckBoxes(form)
{
if (
form.checkbox.checked == false)
{
alert ("You must select a checkbox!")
return false;
} else {
return true;
}
}


<form method="post" id=form name=form onsubmit="return checkCheckBoxes(this);">

Thank you!!

BestZest
01-02-2003, 11:03 AM
I guess you've got multiple checkboxes from what your saying. You could use a loop to ceck the boxes. All the check boxes will need to be named similarly.
Code:
for(i=0;i<box.length;i++){
if(document.form1.box[i].checked==false){
alert("Check all the boxes!");break;}}

This goes through all the checkboxes, seeing if they aren't checked. If one isn't it alerts them, then stops running the loop.

You need to put this in the body as the checkboxes:
<input type="checkbox" name="box">Option 1<br>
<input type="checkbox" name="box">Option 2<br>...

And just repeat for each checkbox. REMEMBER to call them all the same name.