Limit number of characters in input field

2019-01-12 05:18发布

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

7条回答
【Aperson】
2楼-- · 2019-01-12 05:53

make use of maxlength in input tag

<input type="text" maxlength="20" /> 
查看更多
我只想做你的唯一
3楼-- · 2019-01-12 06:01

Maxlength attribute- for browser, that support this feature.
Javascript - for others.

<input class="test-input" type="text" maxlength="12" />
<script>
$('.test-input').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(valLength>maxCount){
        $this.val($this.val().substring(0,maxCount));
    }
}); 
</script>

http://jsfiddle.net/tvpRT/

查看更多
贼婆χ
4楼-- · 2019-01-12 06:03

This should work for you I think.

HTML

<input type="text" name="myText" id="myText" data-maxlength="10" />

jQuery

$('#myText').keyup(validateMaxLength);

function validateMaxLength()
{
        var text = $(this).val();
        var maxlength = $(this).data('maxlength');

        if(maxlength > 0)  
        {
                $(this).val(text.substr(0, maxlength)); 
        }
}
查看更多
我命由我不由天
5楼-- · 2019-01-12 06:04

Let's say it is form input.
you can do it with 'maxlength' attribute but if you say 'using jQuery',
here's the solution.

$('input#limited').attr('maxlength', '3'); 

or you can check every keypress

$('input#limited').keypress(function() {
     /*
     check for 3 or greater than 3 characters.
     If you check for only greater than 3, then it will let
     you write the fourth character because just before writing,
     it is not greater than three.
     */
     if($(this).val().length >= 3) {
        $(this).val($(this).val().slice(0, 3));
        return false;
    }
});
查看更多
我想做一个坏孩纸
6楼-- · 2019-01-12 06:12

As for input field you can use maxlength attribute. If you are looking for div, check the following,

        $(function() {

            $ ('#editable_div').keydown ( function (e) {
                //list of functional/control keys that you want to allow always
                var keys = [8, 9, 16, 17, 18, 19, 20, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 144, 145];

                if( $.inArray(e.keyCode, keys) == -1) {
                    if (checkMaxLength (this.innerHTML, 15)) {
                        e.preventDefault();
                        e.stopPropagation();
                    }
                }
            });

            function checkMaxLength (text, max) {
                return (text.length >= max);
            }
        });

        <div id="editable_div" contentEditable="true" onclick="this.contentEditable='true';" >TEXT BEGIN:</div>

Edit: you should rewrite the checkMaxLength function to ignore tabs and newline

查看更多
男人必须洒脱
7楼-- · 2019-01-12 06:12

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

查看更多
登录 后发表回答