[英]basic JavaScript form validation
I'm testing, getting used to forms. 我正在测试,习惯了表格。 I'm trying to make the JavaScript check the value of the and display a little message next to it if it's not filled in. Simple enough right? 我试图让JavaScript检查的值,如果未填写,则在它旁边显示一条小消息。足够简单了吧?
<script>
function ValidateForm() {
var x = document.forms["Form"]["fName"].value;
If (x==null || x=="") {
document.getElementById("FN").innerHTML = "This field must be filled in"; }
}
</script>
<body>
<form name="Form" onload="ValidateForm()">
First Name: <input type="text" name="fName"> <p id="FN"></p>
Last Name: <input type="text" name="sName"> <p id="SN"></p>
</form>
</body>
Unfortunately, the paragrapgs "FN" and "SN" remain empty onload. 不幸的是,参数“ FN”和“ SN”在加载时仍然为空。 I know this isn't a practical thing here since the validation wont refresh and only runs onload when the fields are bound to be empty already but I'm going to add crap in later that I already know how to use. 我知道这不是实际的事情,因为验证不会刷新,并且仅在字段绑定为空时才在onload上运行,但是稍后我将添加废话,因为我已经知道如何使用。
How can I get this to work? 我该如何工作?
It maybe because you capitalized the letter "I" in if. 可能是因为您将if中的字母“ I”大写了。
If (x==null || x=="") {
should be 应该
if (x==null || x=="") {
Just use the required attribute: 只需使用必填属性:
<form name="Form">
First Name: <input type="text" name="fName" required> <p id="FN"></p>
Last Name: <input type="text" name="sName" required> <p id="SN"></p>
</form>
http://html5doctor.com/html5-forms-introduction-and-new-attributes/#required http://html5doctor.com/html5-forms-introduction-and-new-attributes/#required
Work smart, not hard ;) 聪明地工作,不费力;)
Since this isn't useful... 由于这没有用...
<html>
<head>
<script>
function ValidateForm() {
var x = document.forms["Form"]["fName"].value;
if (x === null || x === "") {
document.getElementById("FN").innerHTML = "This field must be filled in"; }
}
</script>
</head>
<body onload="ValidateForm()">
<form name="Form">
First Name: <input type="text" name="fName"> <p id="FN"></p>
Last Name: <input type="text" name="sName"> <p id="SN"></p>
</form>
</body>
</html>
The first problem is a simple mistake, the If
should be if
: 第一个问题是一个简单的错误, If
应该是if
:
if (x==null || x=="") {
The next problem is that the <form>
tag does not support the onload
event, and as such the function will not run. 下一个问题是<form>
标记不支持onload
事件,因此该功能将无法运行。 Instead do this either when the DOM is loaded or after the <form>
: 而是在加载DOM或<form>
之后执行此操作:
<form name="Form">
First Name: <input type="text" name="fName"> <p id="FN"></p>
Last Name: <input type="text" name="sName"> <p id="SN"></p>
</form>
<script>ValidateForm();</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.