Home >Web Front-end >JS Tutorial >js limit input maximum number of bytes example
This article mainly shares with you an example of limiting the maximum number of input bytes in js. After searching for a long time, I finally found a good solution. I hope it can help everyone.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <script type="text/javascript" src="../js/jquery-1.9.1.min.js"></script> <body> <input type="text" id="nickname" class="nickname" value="" placeholder="请输入您的名字" onkeyup="limitInputCharLen(this,8);"/> <script type="text/javascript"> function limitInputCharLen(str, maxLen) { var w = 0; var tempCount = 0; //length 获取字数数,不区分汉子和英文 for(var i = 0; i < str.value.length; i++) { //charCodeAt()获取字符串中某一个字符的编码 var c = str.value.charCodeAt(i); //单字节加1 if((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) { w++; } else { w += 2; } if(w > maxLen) { str.value = str.value.substr(0, i); break; } } } </script> </body> </html>
Related recommendations:
The above is the detailed content of js limit input maximum number of bytes example. For more information, please follow other related articles on the PHP Chinese website!