Jquery中的自动格式化电话号码

时间:2023-01-14 14:19:20

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/

5 个解决方案

#1


29  

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

既然你正在使用jQuery,你可以试试jquery masked-input-plugin。

There's a jsFiddle for you here where 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:

<input id="ssn"/>

javascript:

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

UPDATE:

Another good one can be found here.

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

#2


5  

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,'$1-');
});

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, '$1-');
    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}\-?)/g the value would become 123-4, 123--45, 123---456 and so on, doubling the dashes each time.

关于正则表达式/(\ d {3})的更多信息\ - ?/ g:这将自己替换3位数的组,然后是破折号。括号创建匹配数字的后引用,用于替换字符串($ 1 - > $ 1是后引用)。请注意,也会替换可选的破折号,但不包括在后引用中。如果输入是123,并且替换模式类似于/(\ d {3})/ g,或/(\ d {3} \ - ?)/ g,则值将变为123-4,123-- 45,123 --- 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

完整的例子:这是小提琴

#3


0  

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.

我在google搜索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'
});

#4


-1  

$('#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"/>

#5


-2  

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($) {

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

});

#1


29  

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

既然你正在使用jQuery,你可以试试jquery masked-input-plugin。

There's a jsFiddle for you here where 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:

<input id="ssn"/>

javascript:

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

UPDATE:

Another good one can be found here.

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

#2


5  

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,'$1-');
});

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, '$1-');
    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}\-?)/g the value would become 123-4, 123--45, 123---456 and so on, doubling the dashes each time.

关于正则表达式/(\ d {3})的更多信息\ - ?/ g:这将自己替换3位数的组,然后是破折号。括号创建匹配数字的后引用,用于替换字符串($ 1 - > $ 1是后引用)。请注意,也会替换可选的破折号,但不包括在后引用中。如果输入是123,并且替换模式类似于/(\ d {3})/ g,或/(\ d {3} \ - ?)/ g,则值将变为123-4,123-- 45,123 --- 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

完整的例子:这是小提琴

#3


0  

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.

我在google搜索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'
});

#4


-1  

$('#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"/>

#5


-2  

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($) {

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

});