发布前的表格要求

时间:2011-06-22 21:51:18

标签: forms post checkbox required

我有一个表单,我希望在表单发布之前需要两个复选框。如果未选中任何一个,我将其设置为显示警告并提示用户检查它们。目前,如果两者都未选中,则可以正常工作。如果仅取消选中第一个复选框,它也可以正常工作。但是,如果第二个复选框(规则复选框)是唯一未选中的复选框 - 表单仍然会发布。

????提前谢谢。

<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>

2 个答案:

答案 0 :(得分:0)

你实际上非常接近,虽然我会说你应该只使用一个函数进行验证,并可能考虑使用javascript框架。它将使javascript更容易使用。

此:

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

应该是这样的:

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

正在运作here on jsfiddle

答案 1 :(得分:0)

你可能想要一个名为validateForm的函数,它将运行验证函数,即每个元素的checkme和checkme2。

话虽如此,您可能还想考虑服务器端验证,因为您希望表单能够与禁用javascript的浏览器一起使用。