Home  >  Article  >  Web Front-end  >  js code to limit the input of N characters in the text box_form effects

js code to limit the input of N characters in the text box_form effects

WBOY
WBOYOriginal
2016-05-16 18:27:401114browse

So what you have to do is
1. First distinguish whether it is a two-byte character or a one-byte character;
2. Use charCodeAt and String.fromCharCode to convert each other.
The code is as follows:

Copy code The code is as follows:

function validatePostponeValue(obj, objLength )
{
var executeResult = false;
var value = obj.value;
var byteLen=0,len=value.length;
var newValue = "";
if (value)
{
for(var i=0; i {
if(value.charCodeAt(i) > 255)
{
byteLen = 2;
if(byteLen <= 18)
{
//alert(String.fromCharCode(value.charCodeAt(i)));
newValue = String.fromCharCode(value.charCodeAt (i));
}
}
else
{
byteLen ;
if(byteLen <= 19)
{
//alert(String. fromCharCode(value.charCodeAt(i)));
newValue = String.fromCharCode(value.charCodeAt(i));
}
}
}
}

if(byteLen <= 0)
{
//alert("Cannot be empty!");
obj.focus();
}
else if(byteLen > objLength )
{
alert("You can only enter up to ten Chinese characters (20 characters).");
obj.focus();
obj.value = newValue;//value.substr (0, objLength -1);
  }
else
{
executeResult = true;
}

return executeResult;
}
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