Phone mask with jQuery and Masked Input Plugin

前端 未结 15 1450
夕颜
夕颜 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:39

    Actually the correct answer is on http://jsfiddle.net/HDakN/

    Zoltan answer will allow user entry "(99) 9999" and then leave the field incomplete

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

提交回复
热议问题