Phone mask with jQuery and Masked Input Plugin

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

    $('.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");
                }
            }
        );
    });
    

提交回复
热议问题