Home > Web Front-end > JS Tutorial > body text

js limits form input length. Chinese characters are two characters_form special effects

WBOY
Release: 2016-05-16 18:04:44
Original
1313 people have browsed it

This effect is integrated into a function. This function accepts 3 parameters:
The first is the ID of the textarea or other text form;
The second is the ID of the displayed input content, which can be left blank;
The third one is the most input character, one Chinese character is 2 characters.
This is just a basic effect, and students are welcome to optimize and improve it.
To get the code, please view the source file of the demo


[Ctrl A select all Note:
If you need to introduce external Js, you need to refresh to execute <script> function lengthLimit(elem, showElem, max){ var elem = document.getElementById(elem); var showElem = document.getElementById(showElem); var max = max || 50;// 最大限度字符,汉字按两个字符计算 function getTextLength(str){// 获取字符串的长度 一个汉字为2个字符 return str.replace(/[^\x00-\xff]/g,"xx").length; }; // 监听textarea的内容变化 if(/msie (\d+\.\d)/i.test(navigator.userAgent) == true) {// 区分IE elem.onpropertychange = textChange; }else{ elem.addEventListener("input", textChange, false); } function textChange(){// 内容变化时的处理 var text = elem.value; var count = getTextLength(text); if(count > max){// 文字超出截断 for(var i=0; i<text.length; i++){ if(getTextLength(text.substr(0, i)) >= max){ elem.value = text.substr(0, i); if(showElem) showElem.innerHTML = elem.value;// 显示输出结果 break; }; } }else{ if(showElem) showElem.innerHTML = elem.value;// 显示输出结果 }; }; textChange();// 加载时先初始化 }; </script>]
Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!