Using the JQuery keyup event:
Copy codeThe Code is as follows:
<Html>
<Head>
<Title> JQuery adds maxlength to textarea </title>
<Script type = "text/javascript" src = "jquery-1.4.js"> </script>
</Head>
<Body>
<Textarea style = "width: 300px; height: 60px;" maxlength = "10"> </textarea>
</Body>
</Html>
<Script type = "text/javascript">
$ (Function (){
$ ("Textarea [maxlength]"). keyup (function (){
Var area = $ (this );
Var max = parseInt (area. attr ("maxlength"), 10); // obtain the value of maxlength
If (max> 0 ){
If (area. val (). length> max) {// The text length of textarea is greater than maxlength
Area. val (area. val (). substr (0, max); // truncate the text of textarea and assign a value again.
}
}
});
});
</Script>
If you only use keyup to judge the maxlength entered by the keyboard, you can still use the mouse to paste it beyond the maxlength limit. You can use the blur event to make a judgment:
Copy codeThe Code is as follows:
$ ("Textarea [maxlength]"). blur (function (){
Var area = $ (this );
Var max = parseInt (area. attr ("maxlength"), 10); // obtain the value of maxlength
If (max> 0 ){
If (area. val (). length> max) {// The text length of textarea is greater than maxlength
Area. val (area. val (). substr (0, max); // truncate the text of textarea and assign a value again.
}
}
});
Text in textarea is truncated after the focus is lost.
After judging through the blur event, there is still a problem. If it is submitted directly after pasting without verifying the length of textarea, it will still submit all the content of textarea.