The example in this article describes how to extend jQuery to realize text prompts on how many bytes can be input. Share it with everyone for your reference, as follows:
1. Add jQuery custom extension
$(function($){ // tipWrap: 提示消息的容器 // maxNumber: 最大输入字符 $.fn.artTxtCount = function(tipWrap, maxNumber){ var countClass = 'js_txtCount', // 定义内部容器的CSS类名 fullClass = 'js_txtFull', // 定义超出字符的CSS类名 disabledClass = 'disabled'; // 定义不可用提交按钮CSS类名 // 统计字数 var count = function(){ var val = lenFor($.trim($(this).val())); if (val <= maxNumber){ tipWrap.html('<span class="' + countClass + '">\u8FD8\u80FD\u8F93\u5165 <strong>' + (maxNumber - val) + '</strong> \u4E2A\u5B57\u8282</span>'); }else{ tipWrap.html('<span class="' + countClass + ' ' + fullClass + '">\u5DF2\u7ECF\u8D85\u51FA <strong>' + (val - maxNumber) + '</strong> \u4E2A\u5B57\u8282</span>'); }; }; $(this).bind('keyup change', count); return this; }; });
Get the number of bytes function
var lenFor = function(str){ var byteLen=0,len=str.length; if(str){ for(var i=0; i<len; i++){ if(str.charCodeAt(i)>255){ byteLen += 3; } else{ byteLen++; } } return byteLen; } else{ return 0; } }
2. Instantiate
<script type="text/javascript"> // demo $(function($){ // 批量 $('.autoTxtCount').each(function(){ $(this).find('.text1').artTxtCount($(this).find('.tips'), 108); }); }); </script>
3 .The corresponding html structure
<div class="form-group"> <div class="col-sm-9"> <label class="col-sm-1 control-label" for="form-field-1"> 内容: </label> </div> </div> <div style="padding-left:100px;" id="autoTxtCount" class="autoTxtCount form-group"> <div > <textarea class="text1" name="content" cols="50" rows="3"><!--{$aData.content}--></textarea> </div> <div> <span class="tips"></span> </div> </div>
4. Some styles
#autoTxtCount { width:500px; } #autoTxtCount .help, #autoTxtCount .help a { color:#999; } #autoTxtCount .tips { color:#999; padding:0 5px; } #autoTxtCount .tips strong { color:#1E9300; } #autoTxtCount .tips .js_txtFull strong { color:#F00; } #autoTxtCount textarea.text1 { width:474px; }
The effect is as follows: