Javascript 在 Jquery 中自动格式化电话号码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10930866/
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 03:37:13  来源:igfitidea点击:

Auto Format Phone Number in Jquery

javascriptjquery

提问by Senthil Sivaramakrishnan

I have one textbox for phone number. My phone number should be XXX-XXX-XXX like this format.

我有一个电话号码文本框。我的电话号码应该是像这种格式的XXX-XXX-XXX。

I got the solution for XXX-XXX-XXX format, but i don't know how to modify that code.

我得到了 XXX-XXX-XXX 格式的解决方案,但我不知道如何修改该代码。

$('#ssn').keyup(function() {
    var val = this.value.replace(/\D/g, '');
    var newVal = '';
    while (val.length > 3) {
      newVal += val.substr(0, 3) + '-';
      val = val.substr(3);
    }
    newVal += val;
    this.value = newVal;
});

http://jsfiddle.net/ssthil/nY2QT/

http://jsfiddle.net/ssthil/nY2QT/

回答by LeftyX

Since you're using jQuery you can try jquery masked-input-plugin.

由于您使用的是 jQuery,您可以尝试使用 jquery masked-input-plugin

There's a jsFiddle for you herewhere you can see how it works.

有一款适合您的jsfiddle在这里,你可以看到它是如何工作的。

The source code for the project on GitHub can be found here.

GitHub 上项目的源代码可以在这里找到。

The implementation is more than simple:

实现不仅仅是简单的:

HTML:

HTML:

<input id="ssn"/>

javascript:

javascript:

$("#ssn").mask("999-999-999");

UPDATE:

更新

Another good one can be found here.

另一个好的可以在这里找到。

回答by Elias Van Ootegem

As far as I can work out, all you really need to do is this:

据我所知,你真正需要做的就是:

$('#ssn').keyup(function()
{
    this.value = this.value.replace(/(\d{3})\-?/g,'-');
});

but this will only work when people enter digits, so I'd suggest an introducing an extra check:

但这仅在人们输入数字时才有效,因此我建议引入额外的检查:

$('#ssn').keyup(function(e) {
  if ((e.keyCode > 47 && e.keyCode < 58) || (e.keyCode < 106 && e.keyCode > 95)) {
    this.value = this.value.replace(/(\d{3})\-?/g, '-');
    return true;
  }
  
  //remove all chars, except dash and digits
  this.value = this.value.replace(/[^\-0-9]/g, '');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="ssn">

A little more on the regex /(\d{3})\-?/g:
This replaces group of 3 digits with itself, followed by a dash. The brackets create a back reference to the matched digits, that is used in the replacement string ($1--> $1 being the back reference).
Note that an optional dash is replaced, too, but not included in the back reference. if the input is 123, and the replace pattern would be something like /(\d{3})/g, or /(\d{3}\-?)/gthe value would become 123-4, 123--45, 123---456and so on, doubling the dashes each time.

关于正则表达式的更多内容/(\d{3})\-?/g
这将用自己替换 3 位数字组,后跟一个破折号。括号创建对匹配数字的反向引用,用于替换字符串($1--> $1 是反向引用)。
请注意,可选的破折号也被替换,但不包括在反向引用中。如果输入是123和取代模式会是这样的/(\d{3})/g,或/(\d{3}\-?)/g该值将成为123-4123--45123---456等等,增加一倍每次破折号。

Warning:
This will give the user some grief, since the arrow keys and such won't work.Luckily, that's an easy fix: Just add the following code at the top of your function:

警告
这会给用户带来一些痛苦,因为箭头键等不起作用。幸运的是,这是一个简单的解决方法:只需在函数顶部添加以下代码:

if (e.keyCode > 36 && e.keyCode < 41)
{
    return true;
}

And the arrows work just fine. for other keys (such as delete, backspace, shift etc...) check this page.

箭头工作得很好。对于其他键(例如删除、退格、移位等),请查看此页面

For a full example: here's the fiddle

一个完整的例子:这是小提琴

回答by Tod Birdsall

I found this question while googling for a way to auto-format phone numbers in Javascript. The accepted answer was not ideal for my needs and a lot has happened in the 6 years since it was originally posted. I eventually found the solution and am documenting it here for posterity.

我在谷歌上搜索一种在 Javascript 中自动格式化电话号码的方法时发现了这个问题。接受的答案并不适合我的需求,自最初发布以来的 6 年里发生了很多事情。我最终找到了解决方案,并在此处记录下来以供后代使用。

Problem

问题

I would like my phone number html input field to auto-format (mask) the value as the user types.

我希望我的电话号码 html 输入字段在用户键入时自动格式化(屏蔽)该值。

Solution

解决方案

Check out Cleave.js. It is a very powerful/flexible and easy way to solve this problem, and many other data masking issues.

查看Cleave.js。这是解决此问题以及许多其他数据屏蔽问题的非常强大/灵活且简单的方法。

Formatting a phone number is as easy as:

格式化电话号码非常简单:

var cleave = new Cleave('.input-element', {
    phone: true,
    phoneRegionCode: 'US'
});

回答by Rahul Vij

$('#ssn').keyup(function() {
        var val = this.value.replace(/\D/g, '');
        var newVal = '';
        for(i=0;i<2;i++){
         if (val.length > 3) {
          newVal += val.substr(0, 3) + '-';
          val = val.substr(3);
        }
        }
        newVal += val;
        this.value = newVal;
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="ssn" maxlength="10"/>

回答by Musharib Khan

You can set input mask on any field in 3 simple steps:

您可以通过 3 个简单的步骤在任何字段上设置输入掩码:

1: First of all call these libraries http://code.jquery.com/jquery-1.7.2.min.js" "https://cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.js"

1:首先调用这些库 http://code.jquery.com/jquery-1.7.2.min.js" " https://cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1 /jquery.maskedinput.js

2: Create simple form like this :

2:创建这样的简单表单:

<form> <input type="text" name="phone" id="phone" /> </form>

3: Then the script code past into your script tag..

3:然后脚本代码过去进入你的脚本标签..

$(document).ready(function($) {

$(document).ready(function($) {

$('#phone').mask("99999-9999999-9",{placeholder:""});

});

});