我正在完成一个关于 Javascript 表单验证的练习。在我的代码中,我有一个包含三列的表:表单名称、表单、验证消息。当表单验证期间发生错误时,该消息将显示在第三列中。当表单元素更改时 - 错误消息应该消失但它不会。似乎根本没有调用 clear() 函数。有人可以帮我吗 - 谢谢!
<html>
<head>
<title>Validation</title>
<script type="text/javascript">
function clear()
{
for(var i in document.getElementsByName("error"))
{
document.getElementsByName("error")[i].innerHTML = "";
}
}
function validate()
{
if(document.Form.Name.value.length < 1)
{
document.getElementsByName("error")[0].innerHTML = "Please enter your full name."
return false;
}
if(document.Form.Address.value.length<3)
{
document.getElementsByName("error")[1].innerHTML = "Please enter full address."
return false;
}
if(document.Form.Phone.value.length <6)
{
document.getElementsByName("error")[2].innerHTML = "Please enter a phone number."
return false;
}
if(document.Form.Email.value.length <5 || "@".search(document.Form.Email.value)==-1)
{
document.getElementsByName("error")[3].innerHTML = "Please enter a valid e-mail address";
return false;
}
}
</script>
</head>
<body>
<h1>Validation</h1>
<p>Enter the following information. When you press the Submit button, the data you entered will be validated.</p>
<form name="Form" onSubmit="return validate()">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="Name" size="20" onchange="clear()" class="Form"></td>
<td><div name="error"></div></td>
</tr>
<tr>
<td>Address</td>
<td><textarea rows="5" columns="20" class="Form" onchange="clear()" name="Address"></textarea></td>
<td><div name="error"></div></td>
</tr>
<tr>
<td>Phone</td>
<td><input type="text" name="Phone" onchange="clear()" size="11" class="Form"></td>
<td><div name="error"></div></td>
</tr>
<tr>
<td>E-mail</td>
<td><input type="text" name="Email" onchange="clear()" size="20" class="Form"></td>
<td><div name="error"></div></td>
</tr>
</table>
<input type="submit" value="Submit" >
<input type="button" value="Clear" onClick="clear();">
</form>
</body>
</html>