js限定多行文本框字符个数

网上摘录简洁的js代码:

<script type="text/javascript">
function checkLength(which) {
    var maxChars = 10; 
    if (which.value.length > maxChars)
    {
        alert("字数过多的提示");
        // 超过限制的字数了就将 文本框中的内容按规定的字数 截取
        which.value = which.value.substring(0,maxChars);
        return false;
    }
    else
    {
        var curr = maxChars - which.value.length; //10 减去 当前输入的
      document.getElementByIdx_x("sy").innerHTML = curr.toString();//显示剩余个数
        return true;
    }
}
</script>

HTML:

 <asp:TextBox ID="TextBox1" runat="server" Height="121px" TextMode="MultiLine"
            Width="317px" onkeyup="checkLength(this);"></asp:TextBox>
        限制字数为:10 剩余字数:<span id="sy" style="color:Red;">10</span>

 

网上拷贝的js代码:

 function getBalance(str) {
        var length = document.getElementById("txtcause").maxLength;
        var strlength = str.length;
        document.getElementById("divapply").innerHTML = "还可以输入" + (length - strlength) + "个字符";
    }
    function maxCheck(ele, maxLength) {
        var maxLengh_Bak = maxLength;
        var length = ele.value.length;
        var i;
        for (i = 0; i < length; i++) {
            if (/^[\u4E00-\u9FA5]+$/g.test(ele.value.charAt(i))) {
                maxLength = maxLength - 2;
            }
            else {
                maxLength--;
            }
            if (maxLength < 0) {
                alert("长度不能超过" + maxLengh_Bak + "个字符");
                ele.value = ele.value.slice(0, i);
                return;
            }
         }
        return;
    }

html:多行文本框

<div id="divapply"> <asp:TextBox ID="txtcause" runat="server" Height="146px" TextMode="MultiLine" MaxLength="30" Width="322px"onkeypress="getBalance(this.value);"  onchange="maxCheck(this,30);"></asp:TextBox></div>

code功能详解:只有当button提交文本内容时,内容超过规定的三十个字符就会有提示框,然后自动将多余的内容删除!

posted @ 2012-07-20 17:01  偶不是大叔  阅读(1811)  评论(0编辑  收藏  举报