jquery adds the code for the MaxLength property to textarea _jquery

Source: Internet
Author: User
KeyUp events via jquery:
Copy Code code as follows:

<title>jquery Add maxlength</title> for textarea
<script type= "Text/javascript" src= "Jquery-1.4.js" ></script>
<body>
<textarea style= "width:300px; height:60px "Maxlength=" ></textarea>
</body>
<script type= "Text/javascript" >
$ (function () {
$ ("textarea[maxlength]"). KeyUp (function () {
var area=$ (this);
var max=parseint (area.attr ("MaxLength"), 10); Gets the value of the MaxLength
if (max>0) {
The text length of the IF (Area.val (). Length>max) {//textarea is greater than maxlength
Area.val (Area.val (). substr (0,max)); Truncate text textarea of a value
}
}
});
});
</script>

If only use the KeyUp only can judge the keyboard input maxlength, uses the mouse to paste or may surpass the maxlength limit, may use the Blur event to make the judgment:
Copy Code code as follows:

$ ("textarea[maxlength]"). blur (function () {
var area=$ (this);
var max=parseint (area.attr ("MaxLength"), 10); Gets the value of the MaxLength
if (max>0) {
The text length of the IF (Area.val (). Length>max) {//textarea is greater than maxlength
Area.val (Area.val (). substr (0,max)); Truncate text textarea of a value
}
}
});

Truncates the textarea text after losing focus.
Through the Blur event, there is still a problem, if the paste directly after the submission without doing the textarea of the length of the case, or will textarea all the content submitted.

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.