Javascript limits the number of characters in the multi-line text input box

Source: Internet
Author: User

For single-line text boxes, we can set the maxlength attribute to limit the maximum number of characters that can be entered:

<Input type = "text" maxlength = "5"/> to limit the maximum number of characters that can be entered in a multi-line text box, you must use a Javascript script. 1. initial solution:<Textarea rows = "4" Cols = "20" onkeydown = "Return maxlength (this, 5);"> </textarea> function maxlength (node, maxcount ){
If (node. value. length> = maxcount ){
Return false;
}
Return true;
} The above solution can contain a maximum of five characters. However, if you have already entered five characters, the system will not respond to any keyboard operation, this will annoy users who want to press the "delete" or "backspace" button to modify the string. 2. Improved solutions:<Textarea rows = "4" Cols = "20" onkeydown = "Return maxleng2( event, 5);"> </textarea> function maxleng2( event, maxcount ){
// The following three steps are performed to ensure compatibility with ff and IE
VaR event = event | window. event;
VaR target = event.tar GET | event. srcelement;
VaR keycode = event. charcode | event. keycode;
// 8-backspace, 46-delete
If (keycode! = 8 & keycode! = 46 ){
If (target. value. length> = maxcount ){
Return false;
}
}
Return true;
} This can meet certain requirements, but if you want to press the "enter" button after entering the maximum character. Considering that onkeydown is pressed on the keyboard, but the text is not input into the text box, and the text has already been input into the text box when onkeyup, We can first allow the user to input and then perform the string truncation policy. 3. A solution for first entering and then truncating characters:<Textarea rows = "4" Cols = "20" onkeyup = "Return maxlength3 (this, 5);"> </textarea>

Function maxlength3 (node, maxcount ){
If (node. value. length> maxcount ){
Node. value = node. value. substr (0, maxcount );
}
}

Code download

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.