Limit of characters in input

1

I want to build a jQuery that applies a limit of 255 characters within input .

My idea and do something like this:

$(".loading").on('input', function () {
  // aqui eu tenho que fazer o bloqueio
});
    
asked by anonymous 27.04.2017 / 18:18

3 answers

3

I would like to suggest some modifications to what has already been proposed:

  • Second, the keydown event of jQuery may be best applied if it is used in a "context", ie instead of onpaste use this oninput , because this way jQuery modifications to the DOM for example pages in Ajax

I generally recommend switching to .on ( $(seletor).on(function()) to old versions of IE) and remove what is added later:

(function () {

    var limite = 10;
    
    function limitaInput(input) {
        if (input.value.length > limite) {
            input.value = input.value.substr(0, limite);
        }
    }
    
    $(document).on("propertychange change keyup", ".loading", function () {
        if (this.timerLimitInput) {
           clearTimeout(this.timer);
        }
    
        this.timerLimitInput = setTimeout(limitaInput, 10, this);//Timeout para evitar conflitos
    });

})();
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script><inputclass="loading">

In this way any manipulation in $(document).on(seletor, function()) will be detected

    
27.04.2017 / 19:16
6

There are many ways to do this, as @Jessika commented:

<input type="text" class="loading" maxlength="255">

If you want to do the same, using jquery

function limitaCampo(campo, tamanho){
    $(campo).attr('maxlength',tamanho);
}

If you want to do the way you presented: just change from 'input' to 'keydown' :

$(".loading").on('keydown', function (e) {
   if($(this).val().length >= 255){
      return false;
   }
});

Here is a 2-character limit snippet:

* I added% w / o to allow backspace and TAB

$(".loading").on('keydown', function(e) {
  if ($(this).val().length >= 2 && e.keyCode != 8 && e.keyCode != 9) {
    return false;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputclass="loading">
    
27.04.2017 / 18:36
1
You can use the keydown event instead of input and use a data-* attribute to set the limit (since you said in the comments that you can not "trust" the maxlength attribute.)

The implementation is very naive, but the idea is this.

$(".loading").on('keydown', function (evt) {
  var qtd = $(this).val().length;
  var limite = $(this).data('limite') || 255;

  if(qtd > limite && evt.keyCode != 8)
    return false;
  
  console.log(qtd, limite);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><textareaclass="loading" data-limite="10"></textarea>
<textarea class="loading"></textarea>
    
27.04.2017 / 18:38