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

jQuery operates textarea input character limit

php中世界最好的语言
Release: 2018-04-19 16:31:33
Original
1851 people have browsed it

This time I will bring you jQueryThe input character limit for operating textarea, what are the notes for operating textarea input character limit with jQuery, the following is a practical case, let’s take a look take a look.

//先判断浏览器是不是万恶的IE
   var bind_name = 'input';//默认事件
   if (navigator.userAgent.indexOf("MSIE") != -1) {
     bind_name = 'propertychange';//不要脸IE独享的事件
   }
   var maxlength = 10;//限定输入字数
   $('#Comment').bind(bind_name, function () {//给textarea绑定事件
     var strlen = $(this).val().replace(/[^\x00-\xff]/g, "aa").length;//读取转换得到长度,中文转换成2个长度,英文空格忽视算1个长度
     $('#aviableCount').text(function () {//一个span显示现在输入多长了
       if (Math.ceil(strlen / 2) > maxlength) {//超过限定长度,只显示最大数
         return maxlength;
       }
       else {
         return Math.ceil(strlen / 2);//为什么要除以2呢,因为前面中文算两个长度,这里我们要转回来,0.5的中文长度算1个中文长度
       }
     });
     if (strlen > maxlength * 2) {//输入超过最大长度,就进行截取
       for (i = 1; i > 0; i++) {
         $(this).val($(this).val().substr(0, $(this).val().length - 1));
         if ($(this).val().replace(/[^\x00-\xff]/g, "aa").length <= maxlength * 2) {
           break;
         }
       }
     }
   })
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

jQuery operation background color gradient animation effect

jQuery plug-in FusionCharts draws pie chart

jquery implements non-dynamic search

The above is the detailed content of jQuery operates textarea input character limit. For more information, please follow other related articles on the PHP Chinese website!

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