<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Mask</title> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js"></script> </head> <body> <input type="text" id="cnpj_cpf"> <script> $(document).ready(function () { maskCnpjCpf('#cnpj_cpf'); }); function maskCnpjCpf(selector) { var CpfCnpjMaskBehavior = function (val) { return val.replace(/\D/g, '').length <= 11 ? '000.000.000-009' : '00.000.000/0000-00'; }, cpfCnpjOptions = { onKeyPress: function(val, e, field, options) { field.mask(CpfCnpjMaskBehavior.apply({}, arguments), options); } }; $(function() { $(selector).bind('paste', function(e) { $(this).unmask(); }); $(selector).bind('input', function(e) { $(selector).mask(CpfCnpjMaskBehavior, cpfCnpjOptions); }); }); } </script> </body> </html>