Textarea does not support the maxlength attribute by default.
Using the JQuery keyup event:
Code
1 2 3 <title> JQuery adds maxlength to textarea </title>
4 <script type = "text/javascript" src = "jquery-1.4.js"> </script>
5 6 <body>
7 <textarea style = "width: 300px; height: 60px;" maxlength = "10"> </textarea>
8 </body>
9 10 <script type = "text/javascript">
11 $ (function (){
12 $ ("textarea [maxlength]"). keyup (function (){
13 var area = $ (this );
14 var max = parseInt (area. attr ("maxlength"), 10); // obtain the value of maxlength
15 if (max> 0 ){
16 if (area. val (). length> max) {// The text length of textarea is greater than maxlength
17 area. val (area. val (). substr (0, max); // truncate the text of textarea and assign a value again.
18}
19}
20 });
21 });
22
23 </script>
24
25
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:
Code
1 $ ("textarea [maxlength]"). blur (function (){
2
3 var area = $ (this );
4 var max = parseInt (area. attr ("maxlength"), 10); // obtain the value of maxlength
5 if (max> 0 ){
6 if (area. val (). length> max) {// The text length of textarea is greater than maxlength
7 area. val (area. val (). substr (0, max); // truncate the text of textarea and assign a value again.
8}
9}
10
11 });
12
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.