为了账号安全,请及时绑定邮箱和手机立即绑定

格式化美国号码的输入字段

格式化美国号码的输入字段

幕布斯7119047 2022-11-03 15:22:07
我的代码有一个小问题,我无法破解它,我想要的格式是 +1 (888) 123-4567 。但是我已经实现了这种 (544)-646-4646 格式。但我无法弄清楚我怎样才能得到已经写好的 +1,当有人输入数字时,其余的应该格式化为上面的例子。所以简而言之,我需要 +1 已经输入并且在用户输入时休息会给出与代码相同的格式。这是代码$(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', '16');    }  });});<html><head><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></head><body><input class="phone-format" value=""  type="text" placeholder="Phone Number"></body></html>
查看完整描述

2 回答

?
函数式编程

TA贡献1807条经验 获得超9个赞

你可以试试这个:


<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


</head>

<body>

<input class="phone-format" value="+1 "  type="text" placeholder="Phone Number">

</body>



</html>

在 js 文件中:


$(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 == 6 && curval.indexOf("(") <= -1) {

      $(this).val(curval.substring(0, 2) + " (" + curval.substring(3) + ")" + "-");

    } else if (curchr == 7 && curval.indexOf("(") > -1) {

      $(this).val(curval + ")-");

    } else if (curchr == 8 && curval.indexOf(")") > -1) {

      $(this).val(curval + "-");

    } else if (curchr == 12){

      $(this).val(curval + "-");

      $(this).attr('maxlength', '16');

    }

  });

});


查看完整回答
反对 回复 2022-11-03
?
侃侃尔雅

TA贡献1801条经验 获得超16个赞

试试jquery 输入掩码插件

您只需要指定您希望输入的掩码/格式,它就可以完成工作。

$(window).load(function()

{

   $('#phone').inputmask({"mask": "+1(999) 999-9999"}); 

});

<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='phone' />


查看完整回答
反对 回复 2022-11-03
  • 2 回答
  • 0 关注
  • 139 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号