Phone mask with jQuery and Masked Input Plugin

前端 未结 15 1511
夕颜
夕颜 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条回答
  •  旧时难觅i
    2020-11-28 07:56

    Here is a jQuery phone number mask. No plugin required. Format can be adjusted to your needs.

    Updated JSFiddle.

    HTML

    JavaScript

    $('#phone-number', '#example-form')
    
    .keydown(function (e) {
        var key = e.which || e.charCode || e.keyCode || 0;
        $phone = $(this);
    
        // Don't let them remove the starting '('
        if ($phone.val().length === 1 && (key === 8 || key === 46)) {
            $phone.val('('); 
            return false;
        } 
        // Reset if they highlight and type over first char.
        else if ($phone.val().charAt(0) !== '(') {
            $phone.val('('+$phone.val()); 
        }
    
        // Auto-format- do not expose the mask as the user begins to type
        if (key !== 8 && key !== 9) {
            if ($phone.val().length === 4) {
                $phone.val($phone.val() + ')');
            }
            if ($phone.val().length === 5) {
                $phone.val($phone.val() + ' ');
            }           
            if ($phone.val().length === 9) {
                $phone.val($phone.val() + '-');
            }
        }
    
        // Allow numeric (and tab, backspace, delete) keys only
        return (key == 8 || 
                key == 9 ||
                key == 46 ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105)); 
    })
    
    .bind('focus click', function () {
        $phone = $(this);
    
        if ($phone.val().length === 0) {
            $phone.val('(');
        }
        else {
            var val = $phone.val();
            $phone.val('').val(val); // Ensure cursor remains at the end
        }
    })
    
    .blur(function () {
        $phone = $(this);
    
        if ($phone.val() === '(') {
            $phone.val('');
        }
    });
    

提交回复
热议问题