You can do it on Blur, I don’t 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');
}
});
I recently had a problem with using several inputs on the same screen, $('.phone-mask')
because the mask was not updated, because the unmask
keeps the selector in a variable, and how I should remask only the input
then it didn’t work, which was my code:
$('.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');
}
});
Did not work because the mask was not created with the selector this
and yes with the selector .phone-mask
, but if I reapplied the mask would apply to all screen inputs and I didn’t want that, then my code got 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);
Try to place an onblur event and count the characters, then if it is 9 digits change the mask
– KaduAmaral