jQuery 如何在键入时更改输入中的电话号码格式?

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

How to change Phone number format in input as you type?

jqueryinputformattingphone-numbermaskedinput

提问by Leon Gaban

My CodePen:http://codepen.io/leongaban/pen/cyaAL

我的 CodePen:http ://codepen.io/leongaban/pen/cyaAL

I have an input field for a phone number which allows up to 20 characters (for international numbers).

我有一个电话号码输入字段,最多允许 20 个字符(对于国际号码)。

I'm also using the Masked input jQuery pluginby Josh Bushto format the phone number in the input to make it 'pretty'.

我还使用了屏蔽输入jQuery插件,乔希·布什的格式输入电话号码,使其“漂亮”。

enter image description here

在此处输入图片说明

  • My problem is that in the requirements when the phone is 10 digits or less, it should use the Masked input formatting.

  • However when the phone number is longer then 10 digits, the formatting should be removed.

  • 我的问题是在要求手机小于等于10位时,应该使用Masked input格式。

  • 但是,当电话号码超过 10 位时,应删除格式。





Here is my current: CodePen, Cell Phone is the input field where I'm trying to accomplish this. Work Phone is an example of the default functionality of the Mask input plugin.

这是我的当前:CodePen,手机是我尝试完成此操作的输入字段。工作电话是掩码输入插件默认功能的一个例子。

How would you go about this problem?

你会如何解决这个问题?

jQuery for Cell Phone input field:

用于手机输入字段的jQuery:

case '2':
    console.log('created phone input');
    $('.new_option').append(myphone);
    $('.added_mobilephone').mask('(999) 999-9999? 9');
    $('.added_mobilephone').keypress(function(event){

      if (this.value.trim().length > 10) {
        console.log('this.value = '+this.value.trim());
        console.log('greater then 10');
        $('.added_mobilephone').mask('99999999999999999999');
      }

      /*if (this.value.length < 9) {
        console.log(this.value);
        console.log('less then 10');
        $('.added_mobilephone').mask('(999) 999-9999? 9999999999');
      } else if (this.value.length > 9) {
        console.log(this.value);
        console.log('greater then 10');
        $('.added_mobilephone').mask('99999999999999999999');
      }*/
    });
    break;

回答by Roop Kumar

$("input[name='phone']").keyup(function() {
    $(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d)+$/, "()-"));
});

This will work for sure :)

这肯定会起作用:)

/* example jquery use */

$("input[name='phone']").keyup(function() {
    $(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d)+$/, "()-"));
});
/* use your css to beautify the form */
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- form input for example user -->
<form>
  <input type="text" name="phone" placeholder="Phone Number" />
</form>

回答by Kevin

You've probably already solved this problem, but it's worth noting for future reference that anyone else with the need to apply multiple masks to a control may want to explore this inputmask plugin.

您可能已经解决了这个问题,但值得注意的是,需要将多个掩码应用于控件的任何其他人可能想要探索这个inputmask 插件以供将来参考。

It has more callbacks, settings and many out of the box mask types(be sure to take a look at the extension files). You can also define multiple masks for a control, and the plugin will try and apply the appropriate mask based on the value.

它有更多的回调、设置和许多开箱即用的掩码类型(一定要看看扩展文件)。您还可以为控件定义多个掩码,插件将尝试根据值应用适当的掩码。

Here is a fiddleto demo the previous statement:

这是演示前面语句的小提琴

$(window).load(function()
{
   var phones = [{ "mask": "(###) ###-####"}, { "mask": "(###) ###-##############"}];
    $('#textbox').inputmask({ 
        mask: phones, 
        greedy: false, 
        definitions: { '#': { validator: "[0-9]", cardinality: 1}} });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.1.62/jquery.inputmask.bundle.js"></script>
<input type='text' id='textbox' />

回答by Atif Tariq

This was very helpful, I only add some code to make it works when user delete some characters, I gave the option of entering only numbers and a max length. This works for me :)

这非常有用,我只添加了一些代码以使其在用户删除某些字符时起作用,我提供了仅输入数字和最大长度的选项。这对我有用:)

$(document).ready(function(){
  /***phone number format***/
  $(".phone-format").keypress(function (e) {
    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
      return false;
    }
    var curchr = this.value.length;
    var curval = $(this).val();
    if (curchr == 3 && curval.indexOf("(") <= -1) {
      $(this).val("(" + curval + ")" + "-");
    } else if (curchr == 4 && curval.indexOf("(") > -1) {
      $(this).val(curval + ")-");
    } else if (curchr == 5 && curval.indexOf(")") > -1) {
      $(this).val(curval + "-");
    } else if (curchr == 9) {
      $(this).val(curval + "-");
      $(this).attr('maxlength', '14');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="phone-format"  type="text" placeholder="Phone Number">

回答by nikolaosinlight

I tried some of the non-plugin answers but they unfortunately had undesirable side effects when editing the phone number. Here is a solution that I ended up creating that is simple and has no special external 3rd party lib dependency:

我尝试了一些非插件答案,但不幸的是,它们在编辑电话号码时产生了不良副作用。这是我最终创建的一个简单的解决方案,没有特殊的外部 3rd 方库依赖项:

  • Does not require any plugins --> just JS and JQuery
  • Filters out non-digits (i.e. noise) automatically
  • Shifts left the phone number digits on deletion of digits
  • Maintains format / does not break down on deletion
  • Does nothing if nothing changes e.g. allows cursor to move left/right to make change vs. other solutions which kept cursor pegged to end
  • 不需要任何插件 --> 只需要 JS 和 JQuery
  • 自动过滤掉非数字(即噪声)
  • 删除数字时左移电话号码数字
  • 保持格式/不会在删除时分解
  • 如果没有任何变化,则不做任何事情,例如允许光标向左/向右移动以进行更改,而其他解决方案使光标固定在结尾

CAVEAT: The phone number considered is only North America which was fine in my case as this was used for local community soccer registration in Canada.

警告:所考虑的电话号码仅适用于北美,这对我来说很好,因为它用于加拿大的当地社区足球注册。

$("input[name='phone_num']").keyup(function() {
  var val_old = $(this).val();
  var val = val_old.replace(/\D/g, '');
  var len = val.length;
  if (len >= 1)
    val = '(' + val.substring(0);
  if (len >= 3)
    val = val.substring(0, 4) + ') ' + val.substring(4);
  if (len >= 6)
    val = val.substring(0, 9) + '-' + val.substring(9);
  if (val != val_old)
    $(this).focus().val('').val(val);
});

回答by Orlando

In your case

在你的情况下

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jasny-bootstrap/3.1.3/js/jasny-bootstrap.min.js"></script>

<input type="text" class="form-control" data-mask="(999) 999-9999">

with jasny bootstrapplugin

使用jasny bootstrap插件

回答by krunal.cp

Check the below answer out.

I created for the TSP code(One of my project) but the similar structure works for the Phone number. Solution is fairly simple.
I am using the KeyCode to the below solution. More information about the keycode could be found here.

检查下面的答案。

我为 TSP 代码(我的项目之一)创建了类似的结构,但电话号码也适用。解决方案相当简单。
我正在将 KeyCode 用于以下解决方案。可以在此处找到有关密钥代码的更多信息。

 $(function () {
    $('#txtphonenumber').keydown(function (e) {
    var key = e.charCode || e.keyCode || 0;
    $text = $(this); 
       if (key !== 8 && key !== 9) {
          if ($text.val().length === 3) {
             $text.val($text.val() + '-');
          }
          if ($text.val().length === 7) {
             $text.val($text.val() + '-');
          }
       }
       return ((key >= 48 && key <= 57) || (key >= 96 && key <= 105) || key == 46 || key == 8 || key == 9 );
      // KeyCode from 48 to 57 are the Numeric characters
      // KeyCode from 96 to 105 are the numpad 0 to numpad 9
      // KeyCode delete 46
      // KeyCode backspace 8
      // KeyCode tab 9
  })
});

回答by woodpav

Here is my solution (for US numbers) that works as you type

这是我的解决方案(适用于美国号码),可在您输入时起作用

const maskPhoneNumber = (s) => {
  let o = '';
  o += s.length >= 3 ? `(${s.substring(0, 3)}` : s;
  o += s.length >= 4 ? `) ${s.substring(3, 6)}` : s.substring(3);
  o += s.length >= 7 ? `-${s.substring(6)}` : '';
  return o;
};

回答by Musaib Memdu

Input type text to input type telephone number. max-length, placeholder using jquery.

输入类型文本以输入类型电话号码。最大长度,使用 jquery 的占位符。

// Used to format phone number and add placeholder and max-length
function phoneFormatter() {
 $(' input[type="text"]').attr({ placeholder : '(___) ___-____' });
  $('input[tabindex="111"]').on('input', function() {
    var number = $(this).val().replace(/[^\d]/g, '')
    if (number.length == 7) {
      number = number.replace(/(\d{3})(\d{4})/, "-");
    } else if (number.length == 10) {
      number = number.replace(/(\d{3})(\d{3})(\d{4})/, "() -");
     
    }
    $(this).val(number)
    $('input[type="text"]').attr({ maxLength : 10 });
    
  });
};

$(phoneFormatter);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="input_111[]" value="" tabindex="111">

回答by CarlosE

Similar solution above but in this script the format is applying meanwhile the user is typing. Adding mask in the phone number - Brazilian Phone Format (00) ?0000-0000. It can be helpful for others as well.

上面类似的解决方案,但在此脚本中,格式在用户输入的同时应用。在电话号码中添加掩码 - 巴西电话格式 (00) ?0000-0000。它也可以对其他人有所帮助。

    //Add mask (00) ?0000-0000 in the phone number - Brazil Format
    $('#iTel').on("keyup blur", function(e){
     var v = $(this).val();
     v = v.replace(/[^\d]/g,'');
     if(v.length < 6){
      v = v.replace(/(\d{2})/, '() ');
     }else if(v.length < 10){
      v = v.replace(/(\d{2})(\d{4})/, '() -');
     }else if(v.length < 11){
      v = v.replace(/(\d{2})(\d{4})(\d{4})/, '() -');    
     }else {
      v = v.replace(/(\d{2})(\d{5})(\d{4})/, '() -');
     }
    $(this).val(v);  
       });
    <!DOCTYPE html>
     <html lang="en">
     <head>
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    </head>
    <body>
    <form method="post" id="cadForm" action="incluir.php">
    <div class="form-row">
     <div class="form-group col-md-12">
     <label for="iTel" class="col-form-label">Phone</label>
     <div class="input-group">
     <span class="input-group-addon"><i class="fa fa-phone" aria-hidden="true"></i></span>
     <input type="text" class="form-control" name="iTel" id="iTel" maxlength="15" placeholder="(xx) ?xxxx-xxxx..." pattern="[(][0-9]{2}[)][\s][0-9]{4,5}[-][0-9]{4}$" title="Please, type only number: (00) ?0000-0000">
     </div>   
    </div>
      </body>
     </html>