我正在编写一个html页面,该页面获取一个名称,地址和一个以练习验证的电话号码。当JavaScript函数试图在输入中获得值的长度时,我会遇到此错误:" usfult typeError:无法读取null的属性'长度"
我不知道nodeValue的含义,但我只想在输入中获取值。
这是JavaScript中代码的一部分,它给了我错误:
function Validate(nameInput, lastNameInput, addressInput, phoneInput)
{
var errorSpan = document.getElementById("errorSpan");
var okSpan = document.getElementById("okSpan");
var nameErrSpan = document.getElementById("nameErrSpan");
var lastNameErrSpan = document.getElementById("lastNameErrSpan");
var addressErrSpan = document.getElementById("addressErrSpan");
var phoneErrSpan = document.getElementById("phoneErrSpan");
var nameLength = nameInput.nodeValue.length;
var lNameLength = lastNameInput.nodeValue.length;
var addressLength = addressIput.nodeValue.length;
var phoneLength = phoneInput.nodeValue.length;
我需要更改以获取输入中的值并测量它们?
这是我的HTML代码:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Validation Form</title>
</head>
<body>
<div>
<span>First name:</span><br />
<input type="text" id="firstName" /> <span id="nameErrSpan" class="nHidden">Name Must Be Between 3 - 10 Letters</span>
<br>
<span>Last name:</span><br />
<input type="text" id="lastName" /> <span id="lastNameErrSpan" class="lnHidden">Last Name Must Be Between 3 - 10 Letters</span>
<br>
<span>Address:</span><br />
<input type="text" id="address" /> <span id="addressErrSpan" class="adHidden">Address Must Be Between 10 - 25 Letters</span>
<br>
<span>Phone number:</span><br />
<input type="text" id="phoneNumber" /> <span id="phoneErrSpan" class="pHidden">Phone Must Be Between 3 - 10 Digits</span>
<br>
<button onclick="Validate(firstName, lastName, address, phoneNumber)">Check</button><br />
<span id="errorSpan" class="hidden">Missing fields</span><br />
<span id="okSpan" class="hidden">All fields are filled</span><br />
<button onclick="reset()">Reset</button><br />
</div>
<link rel="stylesheet" href="registrationForm.css">
<script src="registrationForm.js"></script>
</body>
</html>
要将文本输入input
,您应该使用.value
,而不是.nodeValue
。
var nameLength = nameInput.value.length;
var lNameLength = lastNameInput.value.length;
var addressLength = addressIput.value.length;
var phoneLength = phoneInput.value.length;
input
元素的值可从其value
属性获得。 nodeValue
是> all dom节点的属性,与input
元素无关。