Search code examples
formspostcheckboxrequired

form requirements before posting


I have a form in which I want two check boxes to be required prior to the form posting. If either are not checked, I have it set to display a warning and prompt the user to check them. Currently, it works if both are unchecked. It also works correctly if only the first check box is unchecked. However, if the second check box, the rules check box, is the only one unchecked -- the form still posts.

???? Thanks in advance.

<head>
<title>Untitled Document</title>
<script language="JavaScript" type="text/JavaScript">
function checkme() {
missinginfo = "";
if (!document.team.agree.checked) {
missinginfo += "\n - The entire team must read and agree to the rules";
}
if (missinginfo != "") {
missinginfo ="__________________________________\n" +
"Required information is missing: \n" +
missinginfo + "\n__________________________________" +
"\nEnsure everyone has read the rules and resubmit.";
alert(missinginfo);
return false;
}
else {
return true;
}
}

function checkme2() {
missinginfo2 = "";
if (!document.team.registered.checked) {
missinginfo2 += "\n - Each driver must register individually";
}
if (missinginfo2 != "") {
missinginfo2 ="__________________________________\n" +
"Required information is missing: \n" +
missinginfo2 + "\n__________________________________" +
"\nEnsure everyone has registered individually and resubmit.";
alert(missinginfo2);
return false;
}
else {
return true;
}
}
</script>
</head>

<body>
<form name="team" method="post" action="#" onSubmit="return checkme(), checkme2();">
<table cellpadding="0" cellspacing="0" border="0">
<td colspan="2" align="center"><input type="checkbox" name="registered" value="each_registered"> Each driver is already registered individually.
</td>
</tr>  
<td colspan="2" align="center"><input type="checkbox" name="agree" value="agree_terms"> The team agrees to the rules.</td>
</tr>  
<tr>
<td colspan="2" align="center"><input type="submit" name="submit" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>

Solution

  • You are actually very close although I would say that you should only use a single function for validation and possibly look into using a javascript framework. It will make javascript much easier to use.

    This:

    <form name="team" method="post" action="#" onSubmit="return checkme(), checkme2();">
    

    Should be this:

    <form name="team" method="post" action="#" onSubmit="return checkme() && checkme2();">
    

    It is working here on jsfiddle