以前做项目时候经常用到多行输入框字数的控制以及统计显示的情况,综合了几种情况后现在固定用了这个脚本。
例如 要输入描述textbox
<div> <h3> 描述:</h3> <asp:TextBox runat="server" ID="tbdesciption" Height="200px" TextMode="MultiLine" onkeyup="textCounter(this,'shengyu',500)" onkeydown="textCounter(this,'shengyu',500)" AutoCompleteType="None" Columns="100" MaxLength="1000" Width="500px"></asp:TextBox> </div> <div>您还可以输入:<input type="text" readonly="readonly" style=" width:22px; color:Red; border:0px;" mce_style=" width:22px; color:Red; border:0px;" id="shengyu" />个字</div>
javascript代码:
function textCounter(fieldId, countfieId, maxlimit) { var fieldEle = fieldId; var countfieldEle = document.getElementById(countfieId); if (fieldEle == null || countfieldEle == null) { return false; } if (fieldEle.value.gblen() > maxlimit) // too long... trim it //fieldEle.value = fieldEle.value.substring(0, maxlimit); fieldEle.value = fieldEle.value.gbtrim(maxlimit, ''); else countfieldEle.value = maxlimit - fieldEle.value.gblen(); } String.prototype.gblen = function() { var len = 0; for (var i = 0; i < this.length; i++) { if (this.charCodeAt(i) > 127 || this.charCodeAt(i) == 94) { len += 1; } else { len++; } } return len; } String.prototype.gbtrim = function(len, s) { var str = ''; var sp = s || ''; var len2 = 0; for (var i = 0; i < this.length; i++) { if (this.charCodeAt(i) > 127 || this.charCodeAt(i) == 94) { len2 += 1; } else { len2++; } } if (len2 <= len) { return this; } len2 = 0; len = (len > sp.length) ? len - sp.length : len; for (var i = 0; i < this.length; i++) { if (this.charCodeAt(i) > 127 || this.charCodeAt(i) == 94) { len2 += 1; } else { len2++; } if (len2 > len) { str += sp; break; } str += this.charAt(i); } return str; }
在页面的底部初始化数字显示lable的值,也可以直接写进去。
<mce:script type="text/javascript" language="javascript"><!-- var countfieldEle = document.getElementById("shengyu"); countfieldEle.value = 500; // --></mce:script>
顶部引入js文件即可 非常简单好用