Javascript 带有 jQ​​uery 和屏蔽输入插件的电话屏蔽

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11633726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:36:41  来源:igfitidea点击:

Phone mask with jQuery and Masked Input Plugin

javascriptjqueryinputmaskmaskedinput

提问by JHispa

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

我在使用 jQuery 和Masked Input Plugin屏蔽电话输入时遇到问题。

There are 2 possible formats:

有 2 种可能的格式:

  1. (XX)XXXX-XXXX
  2. (XX)XXXXX-XXXX
  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.

最接近的是 (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?

我想在输入第 10 个数字时得到 (xx)xxxx-xxxx,当我输入第 11 个数字时得到 (xx)xxxxx-xxxx。有可能吗?

回答by Zoltan Toth

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

试试这个 - 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 );
    }
});

回答by Justin

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

这是一个 jQuery 电话号码掩码。不需要插件。格式可以根据您的需要进行调整。

Updated JSFiddle.

更新了 JSFiddle

HTML

HTML

<form id="example-form" name="my-form">
    <input id="phone-number" name="phone-number" type="text" placeholder="(XXX) XXX-XXXX">
</form>

JavaScript

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

回答by Claudio Guirunas

You need a jQuery plugin for the mask works as well.

你也需要一个 jQuery 插件来让遮罩工作。

-- HTML --

-- HTML --

<input type="text" id="phone" placeholder="(99) 9999-9999">
<input type="text" id="telf1" placeholder="(99) 9999*-9999">
<input type="text" id="telf2" placeholder="(99) 9999?-9999">

-- JAVASCRIPT --

-- JAVASCRIPT --

<script src="https://raw.githubusercontent.com/igorescobar/jQuery-Mask-Plugin/master/src/jquery.mask.js"></script>
<script>
$(document).ready(function($){
    $("#phone").mask("(99) 9999-9999"); 
    $("#telf1").mask("(99) 9999*-9999");    
    $("#telf2").mask("(99) 9999?-9999"); 
});
</script>

回答by PH.

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

实际上正确的答案是在http://jsfiddle.net/HDakN/

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

Zoltan 回答将允许用户输入“(99) 9999”,然后将该字段保留为不完整

$("#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 );
    }
});?

回答by HarlemSquirrel

You can use the phone alias with Inputmask v3

您可以在 Inputmask v3 中使用电话别名

$('#phone').inputmask({ alias: "phone", "clearIncomplete": true });

$(function() {
  $('input[type="tel"]').inputmask({ alias: "phone", "clearIncomplete": true });
});
<label for="phone">Phone</label>
    <input name="phone" type="tel">

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/inputmask.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/inputmask.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/inputmask.numeric.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/inputmask.date.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/inputmask.phone.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/jquery.inputmask.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/phone-codes/phone.js"></script>

https://github.com/RobinHerbots/Inputmask#aliases

https://github.com/RobinHerbots/Inputmask#aliases

回答by Igor Escobar

Using jQuery Mask Plugin there is two possible ways to implement it:

使用 jQuery Mask Plugin 有两种可能的方法来实现它:

1- Following Anatel's recomendations: https://gist.github.com/3724610/5003f97804ea1e62a3182e21c3b0d3ae3b657dd9

1- 按照 Anatel 的建议:https: //gist.github.com/3724610/5003f97804ea1e62a3182e21c3b0d3ae3b657dd9

2- Or without following Anatel's recomendations: https://gist.github.com/igorescobar/5327820

2- 或者不遵循 Anatel 的建议:https: //gist.github.com/igorescobar/5327820

All examples above was coded using jQuery Mask Plugin and it can be downloaded at: http://igorescobar.github.io/jQuery-Mask-Plugin/

上面的所有示例都是使用 jQuery Mask Plugin 编码的,可以在以下位置下载:http: //igorescobar.github.io/jQuery-Mask-Plugin/

回答by NovoK

var $phone = $("#input_id");
var maskOptions = {onKeyPress: function(phone) {
    var masks = ['(00) 0000-0000', '(00) 00000-0000'];
    mask = phone.match(/^\([0-9]{2}\) 9/g)
        ? masks[1]
        : masks[0];
    $phone.mask(mask, this);
}};
$phone.mask('(00) 0000-0000', maskOptions);

回答by Brynner Ferreira

With jquery.mask.js

使用 jquery.mask.js

http://jsfiddle.net/brynner/f9kd0aes/

http://jsfiddle.net/brynner/f9kd0aes/

HTML

HTML

<input type="text" class="phone" maxlength="15" value="85999998888">
<input type="text" class="phone" maxlength="15" value="8533334444">

JS

JS

// Function
function phoneMask(e){
    var s=e.val();
    var s=s.replace(/[_\W]+/g,'');
    var n=s.length;
    if(n<11){var m='(00) 0000-00000';}else{var m='(00) 00000-00000';}
    $(e).mask(m);
}

// Type
$('body').on('keyup','.phone',function(){   
    phoneMask($(this));
});

// On load
$('.phone').keyup();

Only jQuery

只有 jQuery

http://jsfiddle.net/brynner/6vbrqe6z/

http://jsfiddle.net/brynner/6vbrqe6z/

HTML

HTML

<p class="phone">85999998888</p>
<p class="phone">8599998888</p>

jQuery

jQuery

$('.phone').text(function(i, text) {
    var n = (text.length)-6;
    if(n==4){var p=n;}else{var p=5;}
    var regex = new RegExp('(\d{2})(\d{'+p+'})(\d{4})');
    var text = text.replace(regex, "() -");
    return text;
});

回答by Raja Rama Mohan Thavalam

I was developed simple and easy masks on input field to US phone format jquery-input-mask-phone-number

我在输入字段上开发了简单易用的掩码到美国电话格式jquery-input-mask-phone-number

Simple Add jquery-input-mask-phone-numberplugin in to your HTML file and call usPhoneFormat method.

简单 将jquery-input-mask-phone-number插件添加到您的 HTML 文件中并调用 usPhoneFormat 方法。

$(document).ready(function () {
    $('#yourphone').usPhoneFormat({
        format: '(xxx) xxx-xxxx',
    });   
});

Working JSFiddle Link https://jsfiddle.net/1kbat1nb/

工作 JSFiddle 链接https://jsfiddle.net/1kbat1nb/

NPM Reference URL https://www.npmjs.com/package/jquery-input-mask-phone-number

NPM 参考网址https://www.npmjs.com/package/jquery-input-mask-phone-number

GitHub Reference URL https://github.com/rajaramtt/jquery-input-mask-phone-number

GitHub 参考网址https://github.com/rajaramtt/jquery-input-mask-phone-number

回答by Artur Haddad

If you don't want to show your mask as placeholder you should use jQuery Mask Plugin.

如果您不想将掩码显示为占位符,则应使用jQuery Mask Plugin

The cleanest way:

最干净的方法:

var options =  {
    onKeyPress: function(phone, e, field, options) {
        var masks = ['(00) 0000-00000', '(00) 00000-0000'];
        var mask = (phone.length>14) ? masks[1] : masks[0];
        $('.phone-input').mask(mask, options);
    }
};

$('.phone-input').mask('(00) 0000-00000', options);