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