JavaScript文本框统计字数

 1 <html>
 2 <head>
 3     <title>enter</title>
 4     <script language="javascript">
 5         function keypress1() //text输入长度处理 
 6         {
 7             var text1 = document.getElementById("mytext1").value;
 8             var len = 15 - text1.length;
 9             var show = "你还可以输入" + len + "个字";
10             document.getElementById("name").innerText = show;
11         }
12         function keypress2() //textarea输入长度处理 
13         {
14             var text1 = document.getElementById("myarea").value;
15             var len; //记录剩余字符串的长度 
16             if (text1.length >= 300) //textarea控件不能用maxlength属性,就通过这样显示输入字符数了 
17             {
18                 document.getElementById("myarea").value = text1.substr(0, 300);
19                 len = 0;
20             } else {
21                 len = 300 - text1.length;
22             }
23             var show = "你还可以输入" + len + "个字";
24             document.getElementById("pinglun").innerText = show;
25         }
26     </script>
27 </head>
28 <body>
29     <center>
30         <div style="text-align:left;">
31             <h3>昵称:</h3>
32             <input type="text" id="mytext1" maxlength=15 onKeyUp="keypress1()" />
33             <font color="gray"><label id="name">你还可以输入15个字</label></font>
34             <h3>评论内容:</h3>
35             <br>
36             <textarea id="myarea" style="height:100px;width:200px;overflow-x:hidden;overflow-y:hidden"
37             onKeyUp="keypress2()" onblur="keypress2()">
38             </textarea>
39             <font color="gray"><label id="pinglun">你还可以输入300个字</label></font>
40         <div>
41     </center>
42 </body>
43 </html>


此代码来自网络收集,非本博主原创

posted @ 2015-10-22 17:45  InkYi  阅读(620)  评论(0编辑  收藏  举报