In many web sites have such a function, that is, you can limit the number of text boxes in the input text, some words not more than how many words, some text can not be less than how many words, the basic principle is the same, the following describes how to use JS to implement this function, code examples are as follows: <! DOCTYPE html>
<meta charset= "Utf-8" >
<meta name= "Author" content= "http://www.51texiao.cn/"/>
<title> Ant Tribe </title>
<script type= "Text/javascript" >
Window.onload=function ()
{
var Textarea=document.getelementbyid ("MyText");
Textarea.onkeyup=function ()
{
Checkmax (textarea,10);
}
}
function Checkmax (textarea,maxlength)
{
var Str=textarea.value;
var strlen=str.length;
if (strlen>maxlength)
{
Alert (' Word count exceeds limit ');
Eval (Textarea.value=str.substr (0,maxlength));
}
}
</script>
<body style= "Text-align:center" >
<textarea name= "TextField" cols= "rows=" id= "MyText" ></textarea>
</body>
The above code implements the limit text input quantity function, and can intercept the text entered in the text box to the specified quantity. A brief introduction to the implementation process:
The core of the implementation of the function is the Checkmax () function, which has two parameters, one parameter is the object to limit the number of input text, and the other is the number to limit.
The functions in vivo of the Checkmax () function are described as follows:
var Str=textarea.value;
Gets the input value in the text box, and calculates the length of the input value. The following if statement is used to determine whether the length of the current input text exceeds the specified limit length, if more than a warning box pops up, and the excess portion is truncated by substr ().
Three. Window.onload=function () {...} The function is that the code in the function body can be executed after the document is loaded, otherwise, the code is executed sequentially, causing document.getElementById ("MyText") to get the object. The event handler is then bound for the onkeyup event of the text box.
How text boxes implement limit input word count effects