直接粘贴到html文件便可看到效果
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta 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> <form> <table> <tr> <td>职业:</td> <td> <input type="text" "checkField(this.value,20,'profession')"/> <input type="text" "checkField(this.value,100,'interest')"/> <input "checkField(this.value,40,'address')" type="text" /> </td> </tr> </table> <div> <button type="reset" "refresh()" > 重置 </button> <button type="submit" "return checkNull()" > 提交 </button> </div> </form> </div> </body> </html>
以上所述是小编给大家介绍的js form表单input框限制20个字符,10个汉字详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
您可能感兴趣的文章: