码迷,mamicode.com
首页 > 其他好文 > 详细

限制Text-Area域中的字符的个数

时间:2015-12-14 20:59:56      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

<textarea id="mytextarea"></textarea>

<script>
jQuery.fn.maxLength = function(max){
    this.each(function(){
        var type = this.tagName.toLowerCase();
        var inputType = this.type? this.type.toLowerCase() : null;
        if(type == "input" && inputType == "text" || inputType == "password"){
            //应用标准的maxLength
            this.maxLength = max;
        }else if(type == "textarea"){
            this.onkeypress = function(e){
                var ob = e || event;
                var keyCode = ob.keyCode;
                var hasSelection = document.selection? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;
                return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);
            };
            this.onkeyup = function(){
                if(this.value.length > max){
                    this.value = this.value.substring(0,max);
                }
            };
        }
    });
};
//use
$(‘#mytextarea‘).maxLength(10);
</script>

 

限制Text-Area域中的字符的个数

标签:

原文地址:http://www.cnblogs.com/weixin186/p/5046179.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!