Jquery code for adding the maxlength attribute to textarea

Source: Internet
Author: User

Using the jquery keyup event: CopyCode The 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.

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.