Limit. js Code
Copy codeThe Code is as follows:
// Txt: jquery object in the text box
// Limit: the maximum number of words.
// Isbyte: true: the number of limit bytes; false: the number of limit characters.
// Cb: callback function. The parameter is the number of words that can be entered.
Function InitLimit (txt, limit, isbyte, cb ){
Txt. keyup (function (){
Var str = txt. val ();
Var charLen;
Var byteLen = 0;
If (isbyte) {// original blog: blog.csdn.net/bluceyoung
For (var I = 0; I <str. length; I ++ ){
If (str. charCodeAt (I)> 255 ){
ByteLen + = 2;
} Else {
ByteLen ++;
}
}
CharLen = Math. floor (limit-byteLen)/2 );
} Else {
ByteLen = str. length;
CharLen = limit-byteLen;
}
Cb (charLen );
});
}
Page code:
Copy codeThe Code is as follows:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta content = "text/html; charset = UTF-8" http-equiv = "Content-Type"/>
<Script src = "http://code.jquery.com/jquery-1.8.2.min.js" type = "text/javascript">
</Script>
<Script type = "text/javascript" src = "limit. js"> </script>
<Script type = "text/javascript">
$ (Document). ready (function (){
InitLimit ($ ("# txt"), 10, true, function (c ){
If (c> = 0 ){
$ ("# Show"). val ("You can also enter" + c + "characters ");
} Else {
$ ("# Show"). val ("more than" + (-c) + "characters ");
}
});
InitLimit ($ ("# txt1"), 10, true, function (c ){
If (c> = 0 ){
$ ("# Show1"). val ("You can also enter" + c + "characters ");
} Else {
$ ("# Show1"). val ("more than" + (-c) + "characters ");
}
});
});
</Script>
</Head>
<Body>
<Input type = "text" id = "txt"/> <input id = "show" type = "text"/> <br/>
<Input type = "text" id = "txt1"/> <input id = "show1" type = "text"/>
</Body>
</Html>