Through JQuery’s keyup event:
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:
$("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.