There is an example in javascript that is easy to find on the internet, I’ve used in a project.
Javascript
function mascaraMutuario(o,f){
v_obj=o
v_fun=f
setTimeout('execmascara()',1)
}
function execmascara(){
v_obj.value=v_fun(v_obj.value)
}
function cpfCnpj(v){
//Remove tudo o que não é dígito
v=v.replace(/\D/g,"")
if (v.length <= 14) { //CPF
//Coloca um ponto entre o terceiro e o quarto dígitos
v=v.replace(/(\d{3})(\d)/,"$1.$2")
//Coloca um ponto entre o terceiro e o quarto dígitos
//de novo (para o segundo bloco de números)
v=v.replace(/(\d{3})(\d)/,"$1.$2")
//Coloca um hífen entre o terceiro e o quarto dígitos
v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2")
} else { //CNPJ
//Coloca ponto entre o segundo e o terceiro dígitos
v=v.replace(/^(\d{2})(\d)/,"$1.$2")
//Coloca ponto entre o quinto e o sexto dígitos
v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3")
//Coloca uma barra entre o oitavo e o nono dígitos
v=v.replace(/\.(\d{3})(\d)/,".$1/$2")
//Coloca um hífen depois do bloco de quatro dígitos
v=v.replace(/(\d{4})(\d)/,"$1-$2")
}
return v
}
Using
<html>
<head>
<title>Máscara Javascript de CNPJ e CPF no Mesmo Campo do Formulário</title>
</head>
<body>
<form>
<input type='text' name='cpfcnpj' onkeypress='mascaraMutuario(this,cpfCnpj)' onblur='clearTimeout()'>
</form>
</body>
</html>
Did you put jQuery Masked Input in your solution as well? Without it, it won’t even work.
– Leonel Sanches da Silva
put yes, what is happening is the following, when I start typing it calls the mask, but the numbers do not leave the first field EX. x__..-__ (always q I type only the "x" changes and does not fill the whole field)
– Jefferson
http://answall.com/questions/94956/m%C3%A1scara-para-Cpf-e-cnpj-no-mesmo-campo Same question
– DiChrist