目标:我已经制作了一个包含 3 个字段的表单,我希望如果表单中甚至还有一个空字段,它会被识别并打印一条错误消息(对于每个空字段)(不警告),并提交表单取消。错误消息最初是隐藏的,只有在字段为空时才应使其可见。
问题:停止提交的代码不起作用。请发布任何错误。如果只使用 alert(),它可以工作,并删除代码以显示和删除隐藏的 validaeFormOnSubmit() 和 validateEmpty()。
形式:
<form action="start.php" method="post" onsubmit="return validateFormOnSubmit(this)" >
<table>
<tbody>
<tr>
<td><label for="fname">Team Name:</label><br></td>
<td><input name="fname" type="text" autocomplete="off">  <div id="1"> Field is
required
</div></td>
</tr>
<tr>
<td><label for="contact">Contact 1 :</label> </td>
<td><input type="text" maxlength = "10" name="contact" >  <div id="2"> Field
is required </div></td>
</tr>
<tr>
<td><label for="contact2">Contact 2:</label> </td>
<td><input type="text" maxlength = "10" name="contact2" >  <div id="3"> Field is
required </div></td>
</tr>
<tr>
<td> </td>
<td><input name="Submit" value="Send" type="submit" ></td>
<td> </td>
</tr>
</tbody>
</table>
</form>
脚本
<script >
$(document).ready(function () {
var i;
for(i=1;i<=3;i++)
{
var k='#'+i;
$(k).hide();}
});
function validateFormOnSubmit(theForm) {
var reason = "";
reason += validateEmpty(theForm.fname,1);
reason += validateEmpty(theForm.contact,2);
reason += validateEmpty(theForm.contact2,3);
if (reason != "") {
return false;
}
return true;
}
function validateEmpty(fld,k) {
var error = "";
if (fld.value.length == 0) {
fld.style.background = 'Yellow';
error = "error";
var k='#'+i;
$(k).show();
} else {
fld.style.background = 'White';
var k='#'+i;
$(k).hide();
}
return error;
}
</script>