javascriptjqueryinputmaskmaskedinput

Phone mask with jQuery and Masked Input Plugin


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?


Solution

  • Try this - http://jsfiddle.net/dKRGE/3/

    $("#phone").mask("(99) 9999?9-9999");
    
    $("#phone").on("blur", function() {
        var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );
    
        if( last.length == 3 ) {
            var move = $(this).val().substr( $(this).val().indexOf("-") - 1, 1 );
            var lastfour = move + last;
            var first = $(this).val().substr( 0, 9 );
    
            $(this).val( first + '-' + lastfour );
        }
    });