Home>

js to determine the length of the input string example code (Chinese characters count two characters,Alphanumeric count)

When entering text,Due to database table field length limitations, submissions fail,So thought of this method validation.

Not much nonsense on the code:

<html>
<head>
  <title>js determines the length of the input string (Chinese characters count as two characters,Alphanumeric counts)</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">
    //Get string length (Chinese characters count as two characters,Alphanumeric count)
    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;
    }
    //verify the length of the text in the edit box as soon as the keyboard is raised,The maximum character length can be set as required
    function checklength (obj) {
      var maxchars=80;//maximum number of characters
      var curr=maxchars-getbytelen (obj.value);
      if (curr>0) {
        document.getelementbyid ("checklen"). innerhtml=curr.tostring ();
      } else {
        document.getelementbyid ("checklen"). innerhtml="0";
        document.getelementbyid ("subject"). readonly=true;
      }
    }
  </script>
</head>
<body>
  <div>
    <textarea maxlength="80" onkeyup="checklength (this)" accesskey="1" tabindex="11"></textarea>
    <span>can also be entered
    <strong>80</strong>
      Characters
    </span>
    <span></span>
  </div>
</body>
</html>
  • Previous AngularJS basic ng-model-options directive simple example
  • Next JS method for randomly taking out several array elements from an array