You can do this in blur , I do not see a better alternative. That is, do the following:
$('#fone').mask('(00) 0000-00009');
$('#fone').blur(function(event) {
if($(this).val().length == 15){ // Celular com 9 dígitos + 2 dígitos DDD e 4 da máscara
$('#fone').mask('(00) 00000-0009');
} else {
$('#fone').mask('(00) 0000-00009');
}
});
Recently I had a problem with using multiple inputs on the same screen, $('.phone-mask')
because the mask was not updated, because unmask
saves the selector in a variable, and how should I remask only the current input
so it did not work, ie my code that was:
$('.phone-mask').mask('(00) 0000-00009');
$('.phone-mask').blur(function(event) {
if($(this).val().length == 15){ // Celular com 9 dígitos + 2 dígitos DDD e 4 da máscara
$(this).mask('(00) 00000-0009');
} else {
$(this).mask('(00) 0000-00009');
}
});
It did not work because the mask was not created with the this
selector but with the .phone-mask
selector, but if I reapplied the mask would apply to all of the onscreen inputs and I did not want this, so my code stayed like this:
$('.phone-mask').each(function(i, el){
$('#'+el.id).mask("(00) 00000-0000");
})
function updateMask(event) {
var $element = $('#'+this.id);
$(this).off('blur');
$element.unmask();
if(this.value.replace(/\D/g, '').length > 10) {
$element.mask("(00) 00000-0000");
} else {
$element.mask("(00) 0000-00009");
}
$(this).on('blur', updateMask);
}
$('.phone-mask').on('blur', updateMask);