Ericson Willians
Ericson Willians

Reputation: 7845

Is there a way to apply a mask on keydown? (JQuery)

I have this mask:

$(".cep").mask("99999-999");

Nevertheless, when I hold a number key, like 1, it fills the input text really fast, in a way that the mask is ignored (Instead of "11111-111", it fills like "111111111"), and this is immeasurably atrocious and bug-prone when combined with events such as change or keydown.

Anyway, is there a way to apply the mask on keydown, so that the user can hold to death the button and be bound to it??

Here's the class on HTML:

<div class="input text col-sm-6 col-xs-6 required">
    <input name="data[Fornecedor][cep]" placeholder="* CEP" maxlength="20" type="text" id="FornecedorCep" required="required" class="cep">
</div>

Upvotes: 0

Views: 4979

Answers (2)

Josh Toth
Josh Toth

Reputation: 764

I'm totally spit-balling here - I don't know what mask() actually is, if it's a plugin you might have to edit it, but you could set a very fast interval to apply it when they hit a key, and then kill the interval on keyup.

Something like this:

   var maskInterval = null;
   $('.cep').on('keydown', function()
   {
      maskInterval = setInterval(function()
      {
            // Do whatever it takes to apply the mask here
            $('.cep').mask();
      }, 25);
   }).on('keyup', function()
   {
      clearInterval(maskInterval);
   });

Upvotes: 1

Mi-Creativity
Mi-Creativity

Reputation: 9654

try this: - untested

$('.cep').on('keydown keypress input blur', function(){
     $(this).mask("99999-999");
});

Upvotes: 2

Related Questions