Limit number of characters in input field

前端 未结 9 863
Happy的楠姐
Happy的楠姐 2020-11-30 12:28

I want to use jquery to limit the number of characters in an editable div (or form input).

相关标签:
9条回答
  • 2020-11-30 13:00

    If you want to make use of JQuery you can write something yourself or just use an existing plugin such as this one.

    But I agree with dku.rajkumar... What is wrong with using the maxlength attribute?

    <input type="text" maxlength="15" />
    

    If you're the biggest JQuery fan ever though and desperately want to set a maxlength to all of the input fields at once do something like:

    $(document).ready(function() {
       $('input[type="text"]').attr({ maxLength : 15 });
    });
    

    Just keep in mind though that this method (the JQuery one) will not work for people who have (for any reason whatsoever) JavaScript disabled. While the maxlength attribute of the input tag works for everybody on all browsers.

    0 讨论(0)
  • 2020-11-30 13:03
    <input type="text" maxlength="20" id="alert_title"/>
    
    $('#alert_title').unbind('keyup change input paste').bind('keyup change input paste',function(e){       
            var $this = $(this);
    
            var val = $this.val();
            var valLength = val.length;
            var maxCount = $this.attr('maxlength');
            if(typeof maxCount == "undefined"){
                $this.attr('maxlength',100);
            }
            if(valLength>maxCount){
                $this.val($this.val().substring(0,maxCount));
            }
        }); 
    
    0 讨论(0)
  • 2020-11-30 13:07

    just use attribute called "maxlength". You can read more about input's attributes at w3 input

    0 讨论(0)
提交回复
热议问题