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

限制文本域中字符输入个数

时间:2015-03-13 18:51:52      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

<script type="text/javascript">
    $(function(){
        jQuery.fn.maxLength=function(max){
            return this.each(function(){
                var type=this.tagName.toLowerCase();
                var inputType=this.type?this.type.toLowerCase:null;
                if(type==‘input‘&&inputType=="text"||inputType=="password"){
                    this.maxLength=max;
                }else if (type=="textarea") {
                    this.onkeypress=function(e){
                        var obj=e||event;
                        var keyCode=obj.keyCode;
                        this.onkeyup=function(){
                            if (this.value.length>max) {
                                this.value=this.value.substring(0,max);
                            }
                        }
                    }
                }
            })
        };
        $("#btn").click(function(){
            var vMaxLen=$("input#txt").val();
            var iMaxLen=parseInt(vMaxLen);
            $("#txtarea").maxLength(iMaxLen);
            $("#log").html($("#log").html()+"<p>"+"最大字符个数设定为:"+vMaxLen+"个"+"</p>");
        });
    });
</script>
</head>
<body>
    <p>
        <b>最大输入字符个数</b>
        <input type="text" id="txt" style="width: 32px;" value="10"/>
    </p>
    <p>
        <input type="button" id="btn" value="限制文本域中字符的个数"/>
    </p>
    <div>
        <textarea rows="" cols="" id="txtarea" name="maxLenTextarrea"></textarea>
    </div>
    <div id="log">
        <p>日志记录:</p>
    </div>

限制文本域中字符输入个数

标签:

原文地址:http://blog.csdn.net/colorsunlight/article/details/44243719

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