Just trying to do a simple maximum length of fName
to not exceed over 10.
I've been looking for online examples. Can't find a common ground in anywhere on any examples I find.
I'm able to submit anything except an empty text (because of required)
<head>
<script type="text/javascript">
var x = document.regoForm.fName.value;
if (x > 1)
{
alert( "too big" );
return false;
}
</script>
</head>
<body>
<form name="regoForm" id="regoForm" method="post">
</p>
<p>
<label for="fName">First Name</label>
<input type="text" required placeholder="John" name="fName"
id="fName"/>
</p>
<p>
<input type="submit" value="submit">
</p>
</form>
您应该能够使用像maxlength
这样的内置方法
<input type="text" maxlength="10" required placeholder="John" name="fName" id="fName"/>
I've added an onclick handler to the button, and insert the code into a function.
And if you want to check the length, not the value, then you should use the .length
to get the length of the text.
Try this
<head>
<script type="text/javascript">
function checkNameLength() {
if (document.getElementById('fName').value.length > 10) {
alert("too big");
return false;
}
}
</script>
</head>
<body>
<form name="regoForm" id="regoForm" method="post">
<p>
<label for="fName">First Name</label>
<input type="text" required placeholder="John" name="fName" id="fName"/>
</p>
<p>
<input type="submit" value="submit" id="submitBtn" onclick="return checkNameLength()">
</p>
</form>
</body>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.