jQuery 或 Javascript 自动格式化电话掩码

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

jQuery or Javascript to autoformat phone mask

javascriptjqueryruby-on-railsruby-on-rails-3

提问by nulltek

I have a Rails app that I'm recording a text_fieldas a stringwhich is a phone number that I'd like auto-formatted in the following mask xxx-xxx-xxxx

我有一个 Rails 应用程序,我text_fieldstring它记录为一个电话号码,我希望在以下掩码中自动格式化xxx-xxx-xxxx

I was searching Stack Overflow and found this auto-format-phone-number-in-jquerybut the OP was looking to format a mask of xxx-xxx-xxxand I need to figure out how to do a mask of xxx-xxx-xxxx

我正在搜索 Stack Overflow 并发现这个auto-format-phone-number-in-jquery但 OP 正在寻找格式化掩码,xxx-xxx-xxx我需要弄清楚如何做掩码xxx-xxx-xxxx

I've borrowed a snipped from this answer and it does work but again formats as xxx-xxx-xxxx

我从这个答案中借用了一个片段,它确实有效,但再次格式化为 xxx-xxx-xxxx

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

Can anyone assist me with formatting in the xxx-xxx-xxxxmask?

任何人都可以帮助我在xxx-xxx-xxxx掩码中进行格式化吗?

回答by Ken Holm

I believe this might work.

我相信这可能会奏效。

$(function(){
  $('#call_caller_phone').keyup(function()
  {
     this.value = this.value.replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'--');
    //alert ("OK");
  });
});
#call_caller_phone {
  color: #fff;
  background-color: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="call_caller_phone" type="text">

回答by Raja Rama Mohan Thavalam

I written custom jQuery code , Please check below code snippet

我编写了自定义 jQuery 代码,请检查下面的代码片段

  $("#yourphone").keydown(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 && e.which != 8 && e.which != 0) {
            $(this).val(curval + "-");
        } else if (curchr == 7 && e.which != 8 && e.which != 0) {
            $(this).val(curval + "-");
        }
        $(this).attr('maxlength', '12');
    });

Working fiddle Example https://jsfiddle.net/rajaramtt/kc8Lu3dv/

工作小提琴示例https://jsfiddle.net/rajaramtt/kc8Lu3dv/

Edit: I have developed jquery-input-mask-phone-number plugin, simply include CDN to your HTML file and call the usPhoneFormat method.

编辑:我开发了 jquery-input-mask-phone-number 插件,只需将 CDN 包含到您的 HTML 文件中并调用 usPhoneFormat 方法。

$(document).ready(function () { $('#yourphone').usPhoneFormat();
});

$(document).ready(function () { $('#yourphone').usPhoneFormat();
});

Working JSFiddle Link https://jsfiddle.net/rajaramtt/orpehtxc/1/

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

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 David Atchley

This will allow only numeric input in the text field (and '-'s) and only allow the 10 digits (plus 2 '-'s) for the US style phone numbers. It inserts the dashes as the user types as well. Might be worth looking at compared to doing the whole thing at the end. But, there are good jquery libraries out there to handle input masks as well, masked input plugin.

这将只允许在文本字段中输入数字(和“-”),并且只允许 10 位数字(加上 2 个“-”)用于美式电话号码。它还会在用户键入时插入破折号。与最后做整件事相比,可能值得一看。但是,也有很好的 jquery 库来处理输入掩码,掩码输入插件

$('#phone').keyup(function(ev) {
  var key = ev.which;
  if (key < 48 || key > 57 || key != 45) {
    ev.preventDefault();
  }

  if (this.value.length > 12) {
    this.value = this.value.slice(0, -1);
    return;
  }

  this.value = this.value.replace(/^(\d{3})(\d)/, '-')
    .replace(/^(\d{3}-\d{3})(\d)/, '-');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id='phone' />

回答by dave

function phoneMask() { 
    num = $(this).val().replace(/\D/g,''); 
    $(this).val(num.substring(0,3) + '-' + num.substring(3,6) + '-' + num.substring(6,10)); 
}
$('[type="tel"]').keyup(phonemask)

How it works: take the phone number, get rid of any non-numeric characters. Then, take the first 3 numbers, add a dash, take the next three, add a dash, and take the next four.

工作原理:获取电话号码,去掉任何非数字字符。然后,取前 3 个数字,加一个破折号,取接下来的三个,加上一个破折号,然后取接下来的四个。

I changed the selector to [type="tel"]because you should be setting the input type to telfor phone numbers, and then this function will apply it to all phone number inputs. But if that doesn't suit your needs, change it back to #call_caller_phone

我将选择器更改为 ,[type="tel"]因为您应该将tel电话号码的输入类型设置为,然后此功能会将其应用于所有电话号码输入。但如果这不符合您的需求,请将其改回#call_caller_phone