欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

js form表单input框限制20个字符,10个汉字代码实例

程序员文章站 2022-03-23 12:56:55
直接粘贴到html文件便可看到效果

直接粘贴到html文件便可看到效果

<!doctype html>
<html>
 <head>
  <meta charset="utf-8" />
  <meta http-equiv="x-ua-compatible" content="ie=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
  <script>
   // 这是第一种最寻常的方法
   //定义一个函数
   function checkfield(value, bytelength, attribute) {
    // value是input框的值,bytelength是需求限制的字符,attribute是input的id名
    var newvalue = value.replace(/[^\x00-\xff]/g, "**");
    var length = newvalue.length;
    //当填写的字节数小于设置的字节数
    if (length * 1 <= bytelength * 1) {
     return;
    }
    var limitdate = newvalue.substr(0, bytelength);
    var count = 0;
    var limitvalue = "";
    for (var i = 0; i < limitdate.length; i++) {
     var flat = limitdate.substr(i, 1);
     if (flat == "*") {
      count++;
     }
    }
    var size = 0;
    var istar = newvalue.substr(bytelength * 1 - 1, 1); //校验点是否为“×”
    //if 基点是×; 判断在基点内有×为偶数还是奇数
    if (count % 2 == 0) {
     //当为偶数时
     size = count / 2 + (bytelength * 1 - count);
     limitvalue = value.substr(0, size);
    } else {
     //当为奇数时
     size = (count - 1) / 2 + (bytelength * 1 - count);
     limitvalue = value.substr(0, size);
    }
    alert(
     "最大输入" +
      bytelength +
      "个字节(相当于" +
      bytelength / 2 +
      "个汉字)!"
    );
    document.getelementbyid(attribute).value = limitvalue;
    return;
   }
  </script>
 </head>
 <body>
  <div class="wrap">
   <form>
    <table class="list-style">
     <tr>
      <td style="width:15%;text-align:right;">职业:</td>
      <td>
       <input id="profession" type="text" "checkfield(this.value,20,'profession')" class="textbox length-middle" name="profession"/>
       <input id="interest" type="text" "checkfield(this.value,100,'interest')" class="textbox length-middle" name="interest"/>
       <input id="address" "checkfield(this.value,40,'address')" type="text" class="textbox length-middle" name="address" />
      </td>
     </tr>
    </table>

    <div style="margin:20px 0 0 300px">
     <button
      type="reset"
      style="width:60px;height:30px;margin-right:40px"
      "refresh()"
     >
      重置
     </button>
     <button
      type="submit"
      style="width:60px;height:30px"
      "return checknull()"
     >
      提交
     </button>
    </div>
   </form>
  </div>
 </body>
</html>

以上所述是小编给大家介绍的js form表单input框限制20个字符,10个汉字详解整合,希望对大家有所帮助