Home > Web Front-end > JS Tutorial > JS simple method to limit the number of characters entered in a textarea_javascript skills

JS simple method to limit the number of characters entered in a textarea_javascript skills

WBOY
Release: 2016-05-16 15:36:35
Original
1469 people have browsed it

The example in this article describes how JS simply limits the number of characters entered in a textarea. Share it with everyone for your reference. The details are as follows:

Here is a demonstration of JS limiting the characters in an area to no more than 255, and any excess characters will be intercepted.

The code is as follows:

<script> 
function getStringUTFLength(str) { 
 var value = str.replace(/[\u4e00-\u9fa5]/g," ");
 //将汉字替换为两个空格
 return value.length; 
} 
function leftUTFString(str,len) { 
 if(getStringUTFLength(str)<=len) { 
  return str; 
 }
 var value = str.substring(0,len); 
 while(getStringUTFLength(value)>len) { 
  value = value.substring(0,value.length-1); 
 } 
 return value; 
} 
function count() { 
 var len=255;
 var value = document.getElementById("licenseother").value; 
 if(getStringUTFLength(value)>=len) {  
  document.getElementById("licenseother").value = leftUTFString(document.getElementById("licenseother").value,len); 
 } 
 document.getElementById("result").value = len-getStringUTFLength(document.getElementById("licenseother").value); 
} 
</script> 
<table width="100%"> 
 <tr>
  <td> 
   <textarea cols=100 rows=4 id="licenseother" onkeypress="count()" onkeyup="count()" onblur="count();" onChange="count();"></textarea> 
  </td>
 </tr> 
 <tr>
  <td> 
   本输入框限制输入255个字符(汉字计算为2个字符)  剩余字符数:
   <input readonly type="text" size="3" id="result" value="255"> 
  </td>
 </tr> 
</table> 

Copy after login

I hope this article will be helpful to everyone’s JavaScript programming.

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template