Home > php教程 > PHP源码 > JS判断输入字符串长度实例代码(汉字算两个字符,字母数字算一个)

JS判断输入字符串长度实例代码(汉字算两个字符,字母数字算一个)

PHP中文网
Release: 2016-05-25 17:03:37
Original
1781 people have browsed it

下面小编就为大家带来一篇JS判断输入字符串长度实例代码(汉字算两个字符,字母数字算一个)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

js判断输入字符串长度实例代码(汉字算两个字符,字母数字算一个)

文本输入时,由于数据库表字段长度限制会导致提交失败,因此想到了此方法验证。

废话不多说上代码:

<html>
<head>
  <title>js判断输入字符串长度(汉字算两个字符,字母数字算一个)</title>
  <style type="text/css">
    .pbt {
      margin-bottom: 10px;
    }

    .ie6 .pbt .ftid a, .ie7 .pbt .ftid a {
      margin-top: 1px;
    }

    .cl:after {
      clear: both;
      content: ".";
      display: block;
      height: 0;
      visibility: hidden;
    }
  </style>
  <script type="text/javascript">
    //获取字符串长度(汉字算两个字符,字母数字算一个)
    function getByteLen(val) {
      var len = 0;
      for (var i = 0; i < val.length; i++) {
        var a = val.charAt(i);
        if (a.match(/[^\x00-\xff]/ig) != null) {
          len += 2;
        }
        else {
          len += 1;
        }
      }
      return len;
    }
    // 只要键盘一抬起就验证编辑框中的文字长度,最大字符长度可以根据需要设定
    function checkLength(obj) {
      var maxChars = 80;//最多字符数   
      var curr = maxChars - getByteLen(obj.value);
      if (curr > 0) {
        document.getElementById("checklen").innerHTML = curr.toString();
      } else {
        document.getElementById("checklen").innerHTML = &#39;0&#39;;
        document.getElementById("subject").readOnly = true;
      }
    }
  </script>
</head>
<body>
  <p class="pbt cl">
    <textarea id="subject" maxlength="80" onkeyup="checkLength(this)" accesskey="1" tabindex="11"></textarea>
    <span id="subjectchk">还可输入
    <strong id="checklen" style="color: #FF0000">80</strong>
      个字符
    </span>
    <span id="postNameRule" class="spn_flag_1" style="display: none"></span>
  </p>
</body>
</html>
Copy after login

以上这篇JS判断输入字符串长度实例代码(汉字算两个字符,字母数字算一个)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持PHP中文网。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template