Digitalbush plugin for masks CNPJ and CPF in the same field

3

I use the plugin below in my html fields to make the mascara, I came up with the need to put the cnpj and cpf masks in the same fields, does anyone know how to do this with this plugin?

link

$("#cpf").mask("999.999.999-99");
$("#cnpj").mask("99.999.999/9999-99");

Thank you.

    
asked by anonymous 07.04.2016 / 20:29

2 answers

4

You can use the jquery.inputmask plugin to mask an entry with different formats. The following code defines two formats the first for cpf and the second for cnpj, when the user enters the 15th the mask will change from cpf to cpnj this is done with the keepStatic: true option that 'holds' the format up to the input marry the next.

$("#doc").inputmask({mask: ['999.999.999-99', '99.999.999/9999-99'], keepStatic: true });
    
07.04.2016 / 20:40
2

I've created and used this solution for years in jQuery for the Digitalbush Plugin Maskedinput plugin:

$(".hibridCpf").on('focusin',function(){
    var target = $(this);
    var val = target.val();
    target.unmask();
    val = val.split(".").join("");
    val = val.split("-").join("");
    val = val.split("/").join("");
    target.val(val);
});
$(".hibridCpf").on('focusout',function(){
    var target = $(this);
    var val = target.val();
    val = val.split(".").join("");
    val = val.split("-").join("");
    val = val.split("/").join("");
    if (val.length==11) {
        target.mask("999.999.999-99");
        target.val(val);
    } else {
        if (val.length==14) {
            target.mask("99.999.999/9999-99");
            target.val(val);
        } else {
            target.val('');
        }
    }
});
  

Try this example on jsfiddle .

It is obvious that the solution posted by @rray is by far simpler and recommends, but there are those case in which it is not possible to replace the Mask Plugin of the application by N reasons, then the way and improvise just like I did kkkk ...

This solution server also for ZIP Code fields where the user can enter a Brazilian or American Postal Code, using a similar logic ...

PS: A mascara plugin that I recommend and use is the Mask Plugin created by the Brazilian @ igorescobar (Github) , he put together Mask Input and Mask Money in one with more customization options , worth checking out!

    
24.03.2017 / 18:00