猿问

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

我的代码有一个小问题,我无法破解它,我想要的格式是 +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>


幕布斯7119047
浏览 140回答 2
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 "&nbsp; type="text" placeholder="Phone Number"></body></html>在 js 文件中:$(document).ready(function(){&nbsp; /***phone number format***/&nbsp; $(".phone-format").keypress(function (e) {&nbsp; &nbsp; if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {&nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp; var curchr = this.value.length;&nbsp; &nbsp; var curval = $(this).val();&nbsp; &nbsp; if (curchr == 6 && curval.indexOf("(") <= -1) {&nbsp; &nbsp; &nbsp; $(this).val(curval.substring(0, 2) + " (" + curval.substring(3) + ")" + "-");&nbsp; &nbsp; } else if (curchr == 7 && curval.indexOf("(") > -1) {&nbsp; &nbsp; &nbsp; $(this).val(curval + ")-");&nbsp; &nbsp; } else if (curchr == 8 && curval.indexOf(")") > -1) {&nbsp; &nbsp; &nbsp; $(this).val(curval + "-");&nbsp; &nbsp; } else if (curchr == 12){&nbsp; &nbsp; &nbsp; $(this).val(curval + "-");&nbsp; &nbsp; &nbsp; $(this).attr('maxlength', '16');&nbsp; &nbsp; }&nbsp; });});

侃侃尔雅

试试jquery 输入掩码插件您只需要指定您希望输入的掩码/格式,它就可以完成工作。$(window).load(function(){&nbsp; &nbsp;$('#phone').inputmask({"mask": "+1(999) 999-9999"});&nbsp;});<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' />
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答