javascript – Two jquery masks in a field

Question:

Can someone help me?

I have an input in which it is CPF/CNPJ, how do I make a mask containing two different values ​​for the same field? And how would the code containing an additional phone field look like? In other words, mask the input cpf/cnpj and mask the phone, I only got it from the cpf, I can't get it from the phone together!

<input type="text" name="cpf" id="cpf">
<input type="text" name="tel" id="tel">

$(document).ready(function(){
var SPMaskBehavior = function (val) {
return val.replace(/\D/g, '').length === 11 ? '000.000.000.00' : '00.000.000/0000-01';
},
spOptions = {
onKeyPress: function(val, e, field, options) {
field.mask(SPMaskBehavior.apply({}, arguments), options);
}
};

$('#cpf').mask(SPMaskBehavior, spOptions);
});

https://igorescobar.github.io/jQuery-Mask-Plugin/

Answer:

This code works, extracts from the documentation:

var options =  {
  onKeyPress: function(cpf, e, field, options) { //Quando uma tecla for pressionada
    var masks = ['000.000.000-000', '00.000.000/0000-01']; //Mascaras
    var mask = (cpf.length > 14) ? masks[1] : masks[0]; //Se for de tamanho 11, usa a 2 mascara
    $('#cpf').mask(mask, options); //Sobrescreve a mascara
}};

$('#cpf').mask('000.000.000-000', options); //Aplica a mascara
Scroll to Top
AllEscort