我试图在不将错误消息显示为警报的情况下验证表单。 innerHTML 似乎是我最好的选择。
我已经尝试实现它,但我没有运气。
这是代码。
Javascript:
<script> function validateForm() {
var x = "";
if (document.orderForm.firstName.value = "")
x += "Please enter your first name.";
document.getElementById('error').innerHTML = x;
return false;
}</script>
HTML:
<form name="orderForm" method="post" onsubmit="return validateForm()" action="processForm.html" >
<table>
<tr>
<th colspan="2">Personal Information</th>
</tr>
<tr>
<td>First Name:</td>
<td><input type="text" name="firstName" id="firstName" size="30"></td>
</tr>
</table>
<div name="error" id="error">
</div>
</form>
现在没有错误信息显示。
最佳答案
if (document.orderForm.firstName.value = "")
分配值 ""
给 document.orderForm。 firstName.value
,然后评估为 false 值,因此 if
语句永远不会为真。
使用比较,而不是赋值。 ==
。
在学习的同时,请了解 validators 、 labels 和 CSS 。
关于javascript - 使用 innerHTML 验证表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26550069/