免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1898 | 回复: 1
打印 上一主题 下一主题

[表单] 转帖--限制输入框的长度(汉字解决方案) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2005-12-23 19:39 |只看该作者 |倒序浏览

  1. 限制输入框的长度(汉字解决方案)

  2. <script>
  3. function getStringUTFLength(str) {
  4.     var value = str.replace(/[^x00-xff]/g,"  ");
  5.     return value.length;
  6. }

  7. function leftUTFString(str,len) {
  8.     if(getStringUTFLength(str)<=len)
  9.         return str;
  10.     var value = str.substring(0,len);

  11.     while(getStringUTFLength(value)>len) {
  12.         value = value.substring(0,value.length-1);
  13.     }
  14.     return value;
  15. }

  16. function count() {
  17.     var value = document.getElementById("licenseother").value;
  18.     value = value.replace(/[u4e00-u9fa5]/g,"  ");
  19.     //alert(value.length);
  20.     if(value.length>=255) {
  21.         with(window.event) {
  22.             cancelBubble = true;
  23.             keyCode=0;
  24.             returnValue = false;
  25.         }
  26.         document.getElementById("licenseother").value = leftUTFString(document.getElementById("licenseother").value,8);
  27.     }
  28.     document.getElementById("result").value = 255-getStringUTFLength(document.getElementById("licenseother").value);
  29. }
  30. </script>
  31. <table width="100%">
  32. <tr><td>
  33. 本输入框限制输入255个字符(汉字计算为2个字符:)
  34. </td></tr>
  35. <tr><td>
  36. <textarea cols=80 rows=3 wrap="virtual" id="licenseother" onkeypress="count()" onkeyup="count()" onblur="count();" onChange="count();"></textarea>

  37. </td></tr>
  38. <tr><td>
  39. 剩余字符数:<input type="text" size="3" id="result" value="255">
  40. </td></tr>
  41. </table>
  42. }
复制代码




转帖的,没有测试,不知道在FF中可用不,另外,既然是utf-8,为什么第一行要替换x00-xff为空?

[ 本帖最后由 HonestQiao 于 2005-12-23 22:39 编辑 ]

论坛徽章:
1
技术图书徽章
日期:2013-12-05 23:25:45
2 [报告]
发表于 2005-12-23 22:41 |只看该作者
UTF8开头有这样子的标记吧
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP