文本框限制输入字数的JS

HTML代码:
其中:class="ui-text" 、class="ui-input"、data-num="48"、class="ui-textTips",是必不可少的。
 <div class="div-p ui-text">
     <ul><li></li><li></li><li></li></ul>
     <textarea name="zhufuyu" id="zhufuyu" cols="" rows="" placeholder="" maxlength="48" class="ui-input" data-num="48"></textarea>
    <div style="margin-top: 5px;" class="zhufuyu_text_msg ui-textTips">还可以输入<em>48</em>个字</div>
 </div>
JS代码:
function tipsText(){
    $('.ui-text').each(function(){
        var _this = $(this);
        var elm = _this.find('.ui-input');
        var txtElm = _this.find('.ui-textTips');
        var maxNum = _this.find('.ui-input').attr('data-num') || 500;
        console.log($.support.leadingWhitespace);
        if(!$.support.leadingWhitespace){
            _this.find('textarea').on('propertychange',function(){
                changeNum(elm,txtElm,maxNum);
            });
            _this.find('input').on('propertychange',function(){
                changeNum(elm,txtElm,maxNum);
            });
        } else {
            _this.on('input',function(){
                changeNum(elm,txtElm,maxNum);
            });
        }
    });
}

tipsText();

//获取文字输出字数,可以遍历使用
//txtElm动态改变的dom,maxNum获取data-num值默认为120个字,ps数字为最大字数*2
function changeNum(elm,txtElm,maxNum) {
    //汉字的个数
    //var str = (elm.val().replace(/\w/g, "")).length;
    //非汉字的个数
    //var abcnum = elm.val().length - str;
    total = elm.val().length;
    if(total <= maxNum ){
        texts = maxNum - total;
        txtElm.html('还可以输入<em>'+texts+'</em>个字');
    }else{
        texts = total - maxNum ;
        txtElm.html('已超出<em class="error">'+texts+'</em>个字');
    }
    return ;
}


猜你喜欢

转载自blog.csdn.net/xiao_hu520/article/details/79786840