/*
* 用于统计input、textarea输入字数,
* 使用:1.默认信息显示模式:$("#test).checkInputTextAreaLen();
* 2.重写信息显示模式:$("#test).checkInputTextAreaLen({max:100,tip:'提示信息'});
* */
(function($){
$.fn.checkInputTextAreaLen = function(options){
return this.each(function(){
function countLength(value_para,max){
var rt = ["",""];
var value = ""||value_para;
var curLen = 0;
for (var i=0; i<value_para.length; i++)
{
if (value_para.charCodeAt(i)>127 || value_para.charCodeAt(i)==94) {
curLen += 2;
}else {
curLen ++;
}
if(curLen<=max){
rt[0]+=value_para.charAt(i);
rt[1]=curLen;
break;
}
}
return rt;
};
function showWordCount(para,obj) {//显示字数
var max = para.max;
var tip = para.tip;
var value = obj.val();
var rt = countLength(value,max);
obj.val(rt[0]);
tip=tip.replace("{current}",max-rt[1]).replace("{max}",max);
obj.next("div").html(tip);
};
var defaluts ={
max:100,//默认最大字节数
tip:"提示:限制输入{max}个字,还能输入{current}个字!" //提示信息
};
defaluts = $.extend(defaluts,options);
var _max = defaluts.max;
var _tip = defaluts.tip;
var divTip=$("<div class='textareaTip'></div>");
var _value = $(this).val();
var _length = countLength(_value);
var _tip=_tip.replace("{current}",_length).replace("{max}",_max);
divTip.html(_tip);
$(this).after(divTip);
$(this).next("div").css('display','none');
$(this).keyup(function() {
//alert($(this).val());
showWordCount(defaluts,$(this));
});
$(this).focus(function(){
showWordCount(defaluts,$(this));
$(this).next("div").fadeIn('slow');
});
$(this).blur(function(){
$(this).next("div").fadeOut('slow');
});
});
}
})(jQuery);