Mask Jquery error when typing a letter

Asked

Viewed 91 times

2

I am with the following problem I am using for example the Mask code

 $(document).ready(function(){
 $('.cpf').mask('999.999.999-99');
 });

perfect it works and accepts only numbers, but if I fix any letter it puts in the input o .. - which are the characters of the mask, and I didn’t want anything to be added when I hit any letter.

  • You want only the numbers to appear?

  • this, in fact if I type only the numbers the mask works perfectly, but if I type for example the letter A in the input appears the .. - that would be the mask without the numbers

1 answer

2


Just check if the pressed key is a number. You can use the function isNaN() at an event keydown to return false if the key is not numerical. Also, I created an array with the codes of some control keys so that they do not fall into the if, that is, for them to work in the field, since they are not numerical, but are useful to control the cursor and selection if necessary:

$(document).ready(function(){

   var teclas = [
      8,    // backspace
      16,   // shift
      17,   // ctrl
      35,   // end
      36,   // home
      37,   // ←
      39,   // →
      46,   // delete
      13    // enter
   ];


   $('.cpf').mask('999.999.999-99').on("keydown", function(e){
      
      var key = e.key; // pega o valor da tecla
      var keycode = e.keyCode || e.which; // pega o código da tecla

      if(isNaN(key) && !~teclas.indexOf(keycode)) return false;

   });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.12/jquery.mask.min.js"></script>

<input class="cpf">

In short, if the pressed key does not have a numeric value and its code is not in the array, it will have no effect in the field.

  • It was perfect

  • blz... I only made one correction: the array teclas outside the event.

  • really thanks friend

Browser other questions tagged

You are not signed in. Login or sign up in order to post.