Home >Web Front-end >JS Tutorial >js limit input maximum number of bytes example

js limit input maximum number of bytes example

小云云
小云云Original
2018-03-17 11:30:211303browse

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!

Statement:
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