Copy codeThe Code is as follows:
/* Input and textarea maximum text limit plug-ins
* Modified version. One Chinese Character represents one word and one English half word;
* TextLimit-jQuery plugin for counting and limiting characters for input and textarea fields
*
* Pass '-1' as speed if you don't want the char-deletion effect. (don't just put 0)
* Example: jQuery ("Textarea"). textlimit ('span. counter', 256)
*
* $ Version: 2009.07.25 + r2
* Copyright (c) 2009 Yair Even-Or
* Vsync.design@gmail.com
*/
String. prototype. getBytes = function (){
Var cArr = this. match (/[^ \ x00-\ xff]/ig );
Return this. length + (cArr = null? 0: cArr. length );
};
(Function (jQuery ){
JQuery. fn. textlimit = function (counter_el, thelimit, speed ){
Var charDelSpeed = speed | 15;
Var toggleCharDel = speed! =-1;
Var toggleTrim = true;
Var that = this [0];
Var isCtrl = false;
UpdateCounter ();
Function updateCounter (){
If (typeof that = "object ")
JQuery (counter_el). text (thelimit-Math. ceil (that. value. getBytes ()/2 ));
};
This. keydown (function (e ){
If (e. which = 17) isCtrl = true;
Var ctrl_a = (e. which = 65 & isCtrl = true )? True: false; // detect and allow CTRL + A selects all.
Var ctrl_v = (e. which = 86 & isCtrl = true )? True: false; // detect and allow CTRL + V paste.
// 8 is 'backspace' and 46 is 'delete'
If (this. value. length> = thelimit & e. which! = '8' & e. which! = '46' & ctrl_a = false & ctrl_v = false)
E. preventDefault ();
})
. Keyup (function (e ){
UpdateCounter ();
If (e. which = 17)
IsCtrl = false;
If (this. value. length> = thelimit & toggleTrim ){
If (toggleCharDel ){
// First, trim the text a bit so the char trimming won't take forever
// Also check if there are more than 10 extra chars, then trim. just in case.
If (this. value. length-thelimit)> 10)
That. value = that. value. substr (0, thelimit + 100 );
Var init = setInterval
(
Function (){
If (that. value. length <= thelimit ){
Init = clearInterval (init); updateCounter ()
}
Else {
// Deleting extra chars (one by one)
That. value = that. value. substring (0, that. value. length-1); jQuery (counter_el ). text (Math. ceil (that. value. getBytes ()/2 ));
}
}, CharDelSpeed
);
}
Else this. value = that. value. substr (0, thelimit );
}
});
};
}) (JQuery );