Heim  >  Artikel  >  Web-Frontend  >  限制文本框输入N个字符的js代码_表单特效

限制文本框输入N个字符的js代码_表单特效

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

所以要做的就是
1.  首先区分出来是两个字节的字符还是一个字节的字符;
2.  使用charCodeAt和String.fromCharCode即可进行相互转换。
代码如下:

复制代码 代码如下:

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   {
  //alert(String.fromCharCode(value.charCodeAt(i)));
  newValue += String.fromCharCode(value.charCodeAt(i));
  } 
  }
  else
  {
  byteLen ++;
  if(byteLen   {
  //alert(String.fromCharCode(value.charCodeAt(i)));
  newValue += String.fromCharCode(value.charCodeAt(i));
  }
  }
  } 
  }
 
  if(byteLen   {
  //alert("不能为空!");
  obj.focus();
  }
  else if(byteLen > objLength)
  {
  alert("最多只能输入十个汉字(20个字符)。");
  obj.focus(); 
  obj.value = newValue;//value.substr(0, objLength -1);
  }
  else
  {
  executeResult = true;
  }
 
  return executeResult;
}
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn