|
Sorry, I should have explained it better. I took it you might adapt it to your own needs.
Yes you do call it 'onsubmit' of the form so your opening form tag will need this :
onsubmit="return validate()"
The elements array allows the code to reference every element of the form, for example the first element in the form would be elements[0].
I have commented the script a little better below :
function validate()
{
result=0; // variable to hold number of ticked boxes, start with zero
start=0; // variable to hold position in form of first checkbox in group
end=4; // variable to hold position in form of last checkbox in group
for(i=start;i<end;i++)
{
// find if each box is checked, if it is add one to the result variable, else add zero
// if this is the only form then you can reference it as forms[0]
result += document.forms[0].elements[i].checked ? 1:0;
}
// check if result variable holds a valid number ( 1,2 or 3 )
if(result>0 && result<4)
{
alert("Fine");
return true; // form will be submitted
}
else
{
alert("Problem");
return false; // form will not be submitted
}
}
This approach can be developed further depending on the complexity of the form. For example, the elements array can be used to test the type attribute and act accordingly if you need to cycle through the entire form.
Here is what the form may look like, this would need no alterations to the validate() function above :
<form onsubmit="return validate()" method="post" action="somescript.tcl">
<input name="r_genre[]" type="checkbox">
<input name="r_genre[]" type="checkbox">
<input name="r_genre[]" type="checkbox">
<input name="r_genre[]" type="checkbox">
<input type="submit">
</form>
|