Home  >  Article  >  Web Front-end  >  JQuery code to add maxlength attribute to textarea_jquery

JQuery code to add maxlength attribute to textarea_jquery

WBOY
WBOYOriginal
2016-05-16 18:30:051341browse
Through JQuery’s keyup event:
Copy code The code is as follows:



JQuery adds maxlength to textarea


If only use keyup can only determine the maxlength of keyboard input. Pasting with the mouse can still exceed the maxlength limit. You can use the blur event to make the determination:
Copy code The code is as follows:

$("textarea[maxlength]").blur(function(){
var area=$(this);
var max=parseInt( area.attr("maxlength"),10); //Get the value of maxlength
if(max>0){
if(area.val().length>max){ //The text length of textarea Greater than maxlength
area.val(area.val().substr(0,max)); //Truncate the textarea and reassign it
}
}
});

Truncate the textarea after losing focus.
There is still a problem after judging by the blur event. If it is submitted directly after pasting without verifying the length of the textarea, the entire content of the textarea will still be submitted.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn