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

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

WBOY
WBOYoriginal
2016-05-16 18:27:401114parcourir

所以要做的就是
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;
}
Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn