How text boxes implement limit input word count effects:
In many 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><HTML><Head><MetaCharSet= "Utf-8"><Metaname= "Author"content= "http://www.51texiao.cn/" /><title>Ant Tribe</title><Scripttype= "Text/javascript">window.onload=function(){ vartextarea=document.getElementById ("MyText"); Textarea.onkeyup=function() {Checkmax (textarea,Ten); } } functionCheckmax (textarea,maxlength) {varStr=Textarea.value; varstrlen=str.length; if(strlen>maxLength) {Alert ('The number of words exceeds the limit'); Eval (Textarea.value=Str.substr (0, maxLength)); } } </Script> </Head> <Bodystyle= "Text-align:center"> <H1>Please enter text test function in text box</H1> <textareaname= "TextField"cols= "$"rows= "Ten"ID= "MyText"></textarea> </Body> </HTML>
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.
Original address: http://www.51texiao.cn/javascriptjiaocheng/2015/0405/123.html
How text boxes implement limit input word count effects