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.
You want only the numbers to appear?
– Wictor Chaves
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
– Mauricio Kalfelz