We often see some websites that can detect the number entered by textarea in real time and give a prompt on how many characters can be entered. Next I will introduce the jQuery-based limit text domain wordcount tutorial.
Core code
The Code is as follows: |
Copy code |
JQuery (document). ready (function ($ ){ Var limitnum = 240; Function limiting (obj, limit ){ // Console. log (obj ); Var cnt = obj. parent (). find (". counter> span "); Var txt = $ (obj). val (); Var len = txt. length; Var current = limit-len; Certificate (cnt0000.html (current ); // If the remaining words are less than 0, add class warning If (current <= 0 ){ $ (Cnt). addClass ("warning "); } Else { // Delete the excess text and remove class warning $ (Cnt). removeClass ("warning "); } } If ($ ("# textarea"). length> 0 ){ // Add a counter after textarea. If it is not empty, the existing words are displayed. $ ("# Textarea "). parent (). append ("<p class =" counter "> <span>" + (240-$ ("# textarea "). val (). length) + "</span> characters </p> "); $ ('# Textarea'). keyup (function (){ Limiting ($ (this), 240 ); }); } // Generally, the Chinese characters are double the English values. If ($ ("# textarea_cn"). length> 0 ){ $ ("# Textarea_cn "). parent (). append ("<p class =" counter "> <span>" + (limitnum/2-$ ("# textarea_cn "). val (). length) + "</span> characters </p> "); $ ('# Textarea_cn'). keyup (function (){ Limiting ($ (this), limitnum/2 ); }); } }); |
Example 2
Limit word count input (add Chinese recognition)
The Code is as follows: |
Copy code |
<Script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"> </script> <Script type = "text/javascript"> $ (Function (){ $ ("Textarea"). keyup (); });
Function strLenCalc (obj, checklen, maxlen ){ Var v = obj. val (), charlen = 0, maxlen =! Maxlen? 200: maxlen, curlen = maxlen, len = v. length; For (var I = 0; I <v. length; I ++ ){ If (v. charCodeAt (I) <0 | v. charCodeAt (I)> 255 ){ Curlen-= 1; } } If (curlen> = len ){ $ ("#" Upload checklen#.html ("You can also enter <strong>" + Math. floor (curlen-len)/2) + "</strong> words" ).css ('color ',''); $ ("# SubBtn"). removeAttr ("disabled "); } Else { $ ("#" Pipeline checklen#.html ("exceeds <strong>" + Math. ceil (len-curlen)/2) + "</strong> words" ..css ('color', '# ff0000 '); $ ("# SubBtn"). attr ("disabled", "disabled "); } } </Script> <Textarea tabindex = "11" onkeyup = "strLenCalc ($ (this), 'checklen', 80 ); "value =" "class =" px "name =" subject "id =" subject "> </textarea> <Span id = "checklen"> You can also enter <strong> 40 </strong> Chinese characters </span> <Input type = "submit" id = "subBtn" value = "publish"/> |