jQuery或Javascript自动格式化手机掩码 [英] jQuery or Javascript to autoformat phone mask
问题描述
我有一个Rails应用,正在将text_field
记录为string
,这是我希望在以下掩码xxx-xxx-xxxx
I have a Rails app that I'm recording a text_field
as a string
which is a phone number that I'd like auto-formatted in the following mask xxx-xxx-xxxx
我正在搜索堆栈溢出,并发现此 auto-format-phone-number-in-jquery ,但OP希望格式化xxx-xxx-xxx
的掩码,我需要弄清楚如何制作xxx-xxx-xxxx
I was searching Stack Overflow and found this auto-format-phone-number-in-jquery but the OP was looking to format a mask of xxx-xxx-xxx
and I need to figure out how to do a mask of xxx-xxx-xxxx
我从这个答案中借了一个片段,它确实起作用,但是再次格式化为xxx-xxx-xxxx
I've borrowed a snipped from this answer and it does work but again formats as xxx-xxx-xxxx
$(function(){
$('#call_caller_phone').keyup(function()
{
this.value = this.value.replace(/(\d{3})\-?/g,'$1-');
});
});
有人可以协助我使用xxx-xxx-xxxx
蒙版进行格式化吗?
Can anyone assist me with formatting in the xxx-xxx-xxxx
mask?
推荐答案
我编写了自定义jQuery代码,请检查以下代码段
I written custom jQuery code , Please check below code snippet
$("#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');
});
工作小提琴示例 https://jsfiddle.net/rajaramtt/kc8Lu3dv/
我已经开发了jquery-input-mask-phone-number插件,只需将CDN包含到您的HTML文件中,然后调用usPhoneFormat方法即可.
I have developed jquery-input-mask-phone-number plugin, simply include CDN to your HTML file and call the usPhoneFormat method.
$(document).ready(function(){
$('#yourphone').usPhoneFormat();
});
$(document).ready(function () {
$('#yourphone').usPhoneFormat();
});
有效的JSFiddle链接 https://jsfiddle.net/rajaramtt/orpehtxc/1/
Working JSFiddle Link https://jsfiddle.net/rajaramtt/orpehtxc/1/
NPM参考URL https://www.npmjs.com/包/jquery-input-mask-phone-number
NPM Reference URL https://www.npmjs.com/package/jquery-input-mask-phone-number
GitHub参考URL https://github.com/rajaramtt/jquery-输入掩码电话号码
GitHub Reference URL https://github.com/rajaramtt/jquery-input-mask-phone-number
这篇关于jQuery或Javascript自动格式化手机掩码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!