提问者:小点点

设置美国号码的输入字段格式


我有一个小问题与我的代码,我不能破解它,我想要的格式是+1(888)123-4567。 然而,我已经实现了这种(544)-646-4646格式。 但我不知道如何才能得到+1已经写好了,当有人键入number时,剩下的应该被格式化为上面的例子。

所以用简单的话来说,我需要+1已经被键入,当被用户键入时,rest将给出与代码相同的格式。

这是代码

null

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

null


共2个答案

匿名用户

您可以尝试以下操作:

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

匿名用户

尝试jquery输入掩码插件

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

null

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