2009年11月9日星期一

[转]JS控制输入字符长度

 
 

Sent to you by M.Zhou via Google Reader:

 
 

via 堕落天使 by depravedangel on 11/8/09

 <script language="JavaScript">      <!--      function CutStrLength(str,Ilength)     {         var tmp=0;         var len=0;         var okLen=0         for(var i=0;i<Ilength;i++)         {             if(str.charCodeAt(i)>255)                 tmp+=2             else                 len+=1             okLen+=1             if(tmp+len==Ilength)             {                 return (str.substring(0,okLen));                 break;             }             if(tmp+len>Ilength)             {                 return (str.substring(0,okLen-1)+"");                 break;             }         }     }     function checkFieldLength(fieldName,fieldDesc,fieldLength)     {         var str=document.getElementById(fieldName).value;         var theLen=0;         var teststr='';         for(i=0;i<str.length;i++)         {             teststr=str.charAt(i);             if(str.charCodeAt(i)>255)             theLen=theLen+2;             else             theLen=theLen+1;         }         document.getElementById('showMsg').innerText=theLen;         if(theLen>fieldLength)         {             document.getElementById('showMsg').innerText=fieldDesc;             //alert(fieldDesc+" 的字段长度超过规定长度!");             //document.getElementById(fieldName).focus();             document.getElementById(fieldName).value=CutStrLength(str,fieldLength);             return false;         }         else         {             return true;         }     }     //-->     </script>  </head> <body>     <form method="POST" action="">         <textarea id="testArea" name="testArea" rows="3" cols="22" onkeyup="checkFieldLength('testArea', '超过允许输入的字符个数', 20);"             onchange="checkFieldLength('testArea', '超过允许输入的字符个数', 20);"></textarea>         <div id="testInfo">             已经输入:<span id="showMsg"></span></div>     </form> </body> </html> 


已有 0 人发表留言,猛击->>这里<<-参与讨论


JavaEye推荐




 
 

Things you can do from here:

 
 

没有评论: