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!