Javascript 限制文本域中的字数,能动态提示输入的长度:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>无标题文档</title> <script language="javascript" type="text/javascript"> function checklen(obj) { var lenE = obj.value.length; var lenC = 0; var CJK = obj.value.match(/[\u4E00-\u9FA5\uF900-\uFA2D]/g); if (CJK != null) lenC += CJK.length; var tno = document.getElementById("tno"); tno.innerText = obj.maxlength - lenC - lenE ; if (tno.innerText < 0) { var tmp = 0 var cut = obj.value.substring(0, obj.maxlength); for (var i=0; i<cut.length; i++){ tmp += /[\u4E00-\u9FA5\uF900-\uFA2D]/.test(cut.charAt(i)) ? 2 : 1; if (tmp > obj.maxlength) break; } obj.value = cut.substring(0, i); } } </script> </head> <body> <textarea name="content" id="remark" maxlength="250" onpropertychange="checklen(this)" style="200px;height:300px;"></textarea> <div id="remainstr">最多可以输入250字<br />您还可以输入<span id="tno">250</span>字</div> </body> </html>
不过这种方法只适用于IE,不兼容其他火狐、谷歌、Opera等等。下面我写了一个比较简单的判断字符长度,没有判断是否是双字节。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script language="javascript" type="text/javascript"> function textLimitCheck(thisArea, maxLength, SpanId) { //根据onkeyup事件计算文本框中的字符个数,限制在500以内 if (thisArea.value.length > maxLength) { alert(maxLength + ' 个字限制. \r超出的将自动去除.'); thisArea.value = thisArea.value.substring(0, maxLength); thisArea.focus(); } /*回写span的值,当前填写文字的数量*/ document.getElementById(SpanId).innerHTML = thisArea.value.length; } </script> </head> <body> <textarea id="txtCommentInfo" rows="5" cols="45" onkeyup="textLimitCheck(this,1250,'messageCount');"></textarea> <font>您可以输入1250个字符</font> <span id="messageCount">0</span>/1250 </body> </html>
代码结束。请大家指教。