How to change Phone number format in input as you

2019-01-31 23:44发布

My CodePen: http://codepen.io/leongaban/pen/cyaAL

I have an input field for a phone number which allows up to 20 characters (for international numbers).

I'm also using the Masked input jQuery plugin by Josh Bush to format the phone number in the input to make it 'pretty'.

enter image description here

  • My problem is that in the requirements when the phone is 10 digits or less, it should use the Masked input formatting.

  • However when the phone number is longer then 10 digits, the formatting should be removed.



Here is my current: CodePen, Cell Phone is the input field where I'm trying to accomplish this. Work Phone is an example of the default functionality of the Mask input plugin.

How would you go about this problem?

jQuery for Cell Phone input field:

case '2':
    console.log('created phone input');
    $('.new_option').append(myphone);
    $('.added_mobilephone').mask('(999) 999-9999? 9');
    $('.added_mobilephone').keypress(function(event){

      if (this.value.trim().length > 10) {
        console.log('this.value = '+this.value.trim());
        console.log('greater then 10');
        $('.added_mobilephone').mask('99999999999999999999');
      }

      /*if (this.value.length < 9) {
        console.log(this.value);
        console.log('less then 10');
        $('.added_mobilephone').mask('(999) 999-9999? 9999999999');
      } else if (this.value.length > 9) {
        console.log(this.value);
        console.log('greater then 10');
        $('.added_mobilephone').mask('99999999999999999999');
      }*/
    });
    break;

8条回答
smile是对你的礼貌
2楼-- · 2019-02-01 00:06

You've probably already solved this problem, but it's worth noting for future reference that anyone else with the need to apply multiple masks to a control may want to explore this inputmask plugin.

It has more callbacks, settings and many out of the box mask types(be sure to take a look at the extension files). You can also define multiple masks for a control, and the plugin will try and apply the appropriate mask based on the value.

Here is a fiddle to demo the previous statement:

$(window).load(function()
{
   var phones = [{ "mask": "(###) ###-####"}, { "mask": "(###) ###-##############"}];
    $('#textbox').inputmask({ 
        mask: phones, 
        greedy: false, 
        definitions: { '#': { validator: "[0-9]", cardinality: 1}} });
});
<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='textbox' />

查看更多
淡お忘
3楼-- · 2019-02-01 00:07

I tried some of the non-plugin answers but they unfortunately had undesirable side effects when editing the phone number. Here is a solution that I ended up creating that is simple and has no special external 3rd party lib dependency:

  • Does not require any plugins --> just JS and JQuery
  • Filters out non-digits (i.e. noise) automatically
  • Shifts left the phone number digits on deletion of digits
  • Maintains format / does not break down on deletion
  • Does nothing if nothing changes e.g. allows cursor to move left/right to make change vs. other solutions which kept cursor pegged to end

CAVEAT: The phone number considered is only North America which was fine in my case as this was used for local community soccer registration in Canada.

$("input[name='phone_num']").keyup(function() {
  var val_old = $(this).val();
  var val = val_old.replace(/\D/g, '');
  var len = val.length;
  if (len >= 1)
    val = '(' + val.substring(0);
  if (len >= 3)
    val = val.substring(0, 4) + ') ' + val.substring(4);
  if (len >= 6)
    val = val.substring(0, 9) + '-' + val.substring(9);
  if (val != val_old)
    $(this).focus().val('').val(val);
});
查看更多
甜甜的少女心
4楼-- · 2019-02-01 00:14
$("input[name='phone']").keyup(function() {
    $(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d)+$/, "($1)$2-$3"));
});

This will work for sure :)

查看更多
贪生不怕死
5楼-- · 2019-02-01 00:25

window bottom to top scroll sticky menu using jquery.

  var lastScroll = 0;

  $(document).ready(function($) {

  $(window).scroll(function(){

  setTimeout(function() { 
        var scroll = $(window).scrollTop();
        if (scroll > lastScroll) {

            $("header").removeClass("menu-sticky");

        } 
        if (scroll == 0) {
        $("header").removeClass("menu-sticky");

        }
        else if (scroll < lastScroll - 5) {


            $("header").addClass("menu-sticky");

        }
        lastScroll = scroll;
        },0);
        });
       });
 </script>
查看更多
相关推荐>>
6楼-- · 2019-02-01 00:27

In your case

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jasny-bootstrap/3.1.3/js/jasny-bootstrap.min.js"></script>

<input type="text" class="form-control" data-mask="(999) 999-9999">

with jasny bootstrap plugin

查看更多
够拽才男人
7楼-- · 2019-02-01 00:28

This was very helpful, I only add some code to make it works when user delete some characters, I gave the option of entering only numbers and a max length. This works for me :)

$(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', '14');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="phone-format"  type="text" placeholder="Phone Number">

查看更多
登录 后发表回答