CPF Mask | CNPJ. when loading

Asked

Viewed 821 times

0

I have a script that masks CPF or CNPJ, is working perfectly. but it uses the method onKeyPress, then it only works, when I’m typing. when I bring an object that is CNPJ to show, the field CPF/CNPJ gets like this: 000.000.000-00000. when behind CPF becomes normal, with the mask: 000.000.000-00

The question, is how do I get the CNPJ, with the correct mask when I’m bringing an object?.

My script is this:

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.0/jquery.mask.js"></script>
    <script>
        //Mascara CPF ou CNPJ
        var options = {
            onKeyPress: function (cpf, ev, el, op) {
                var masks = ['000.000.000-000', '00.000.000/0000-00'];
                $('#cnpj_cpf').mask((cpf.length > 14) ? masks[1] : masks[0], op);
            }
        }

        $('#cnpj_cpf').length > 11 ? $('#cnpj_cpf').mask('00.000.000/0000-00', options) : $('#cnpj_cpf').mask('000.000.000-00#', options);
    </script>

The mask I want to show is like this: 00.000.000/0000-00

2 answers

2


Checking out the documentation you will see that the plugin can receive a function as argument. Also checking the code on Github you will see that the parameters passed to the function are:

function minha_funcao(input_value, undefined, element, options) {...}

And seeing the event code onKeyPress, you will see that the parameters passed to your callback follow the same pattern:

function meu_callback(input_value, event, element, options) {...}

That said, a good solution to your problem is to create a function that returns the appropriate mask depending on the argument input_value and use it in creating the mask and also in recreating the mask in the callback of onKeyPress.

Working example:

/**
 * Retorna a máscara correta dependendo da quantidade de números na string
 */
function get_mask(input_value, event, element, options) {
    // Remove caracteres não numéricos
    var numbers = input_value.replace(/\D+/g, '');
    return numbers.length <= 11 ? '000.000.000-000' : '00.000.000/0000-00';
}

// Usa a função `get_mask` para definir a máscara
$('#cnpj_cpf').mask(get_mask, {
    onKeyPress: function (input_value, event, element, options) {
        element.mask(get_mask, options);
    }
});
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.0/jquery.mask.js"></script>

<input id="cnpj_cpf" value="11222333000199"/>

  • worked perfectly. thank you!

1

$('#cnpj_cpf'). length will always return 1 , because it is the amount of elements with id cnpj_cpf in the DOM, and your mask for Cpf will not catch

I believe what you wanted to do was:

$('#cnpj_cpf').val().length > 11 ? $('#cnpj_cpf').mask('00.000.000/0000-00', options) : $('#cnpj_cpf').mask('000.000.000-00#', options);

Browser other questions tagged

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