0

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

???提前致谢。

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

2 回答 2

0

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

这:

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

应该是这样的:

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

在 jsfiddle 上工作

于 2011-06-22T21:55:44.637 回答
0

您可能希望有一个名为 validateForm 的函数,它将为每个元素运行验证函数,即 checkme 和 checkme2。

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

于 2011-06-22T21:55:59.097 回答