用js限制文本框输入最大字符,中文1个英文2个

function checkLength(which) {
    $('#ParameName').on('input', function (e) {
        var $that = $(this),
                limitLen = 12;                            //定义所需字节数
        $that.attr('maxlength', limitLen);
        setTimeout(function () {
            var value = $that.val(),
                reg = /[\u4e00-\u9fa5]{1}/g,             //中文
                notReg = /\w{1}/g;                      //非中文
            var resultCn = value.match(reg);
            var resultEn = value.match(notReg);
            if (resultCn) {
                limitLen = limitLen - (resultCn.length * 2);
            }
            if (resultEn) {

                limitLen = limitLen - resultEn.length;
            }
            if (limitLen <= 0) {
                var finalLen = value.length + limitLen;
                value = value.substring(0, finalLen);
                $that.attr('maxlength', limitLen);
                $that[0].value = value;
            }
        }, 0);
    });
}

 

posted on 2017-03-03 14:36  阿门668  阅读(329)  评论(0)    收藏  举报

导航