Phone mask with jQuery and Masked Input Plugin

前端 未结 15 1506
夕颜
夕颜 2020-11-28 06:54

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

There are 2 possible formats:

  1. (XX)XXXX-XXXX
  2. (
15条回答
  •  无人及你
    2020-11-28 07:34

    The best way to do this is using the change event like this:

    $("#phone")
    .mask("(99) 9999?9-9999")
    .on("change", 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 ); // Change 9 to 8 if you prefer mask without space: (99)9999?9-9999
    
            $(this).val( first + '-' + lastfour );
        }
    })
    .change(); // Trigger the event change to adjust the mask when the value comes setted. Useful on edit forms.
    

提交回复
热议问题