Phone mask with jQuery and Masked Input Plugin

Viewed 291552

I have a problem masking a phone input with jQuery and Masked Input Plugin.

There are 2 possible formats:

  1. (XX)XXXX-XXXX
  2. (XX)XXXXX-XXXX

Is there any way to mask it accepting both cases?

EDIT:

I tried:

$("#phone").mask("(99) 9999-9999"); 
$("#telf1").mask("(99) 9999*-9999");    
$("#telf1").mask("(99) 9999?-9999"); 

But it doesn't works as I would like.

The closest one was (xx)xxxx-xxxxx.

I would like to get (xx)xxxx-xxxx when I type the 10th number, and (xx)xxxxx-xxxx when I type the 11th. Is it posible?

15 Answers

If you don't want to show your mask as placeholder you should use jQuery Mask Plugin.

The cleanest way:

var options =  {
    onKeyPress: function(phone, e, field, options) {
        var masks = ['(00) 0000-00000', '(00) 00000-0000'];
        var mask = (phone.length>14) ? masks[1] : masks[0];
        $('.phone-input').mask(mask, options);
    }
};

$('.phone-input').mask('(00) 0000-00000', options);

Yes use this

$("#phone").inputmask({"mask": "(99) 9999 - 9999"});

Link here

$('.phone').focus(function(e) {
    // add mask
    $('.phone')
        .mask("(99) 99999999?9")
        .focusin(function(event)
        {
            $(this).unmask();
            $(this).mask("(99) 99999999?9");
        })
        .focusout(function(event)
        {
            var phone, element;
            element = $(this);
            phone = element.val().replace(/\D/g, '');
            element.unmask();

            if (phone.length > 10) {
                element.mask("(99) 99999-999?9");
            } else {
                element.mask("(99) 9999-9999?9");
            }
        }
    );
});
Related