How to change Phone number format in input as you type?

孤街浪徒 提交于 2019-12-29 14:17:22

问题


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'.



  • 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;

回答1:


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



回答2:


$("input[name='phone']").keyup(function() {
    $(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d)+$/, "($1)$2-$3"));
});

This will work for sure :)

/* example jquery use */

$("input[name='phone']").keyup(function() {
    $(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d)+$/, "($1)$2-$3"));
});
/* use your css to beautify the form */
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- form input for example user -->
<form>
  <input type="text" name="phone" placeholder="Phone Number" />
</form>



回答3:


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">



回答4:


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



回答5:


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




回答6:


Check the below answer out.

I created for the TSP code(One of my project) but the similar structure works for the Phone number. Solution is fairly simple.
I am using the KeyCode to the below solution. More information about the keycode could be found here.

 $(function () {
    $('#txtphonenumber').keydown(function (e) {
    var key = e.charCode || e.keyCode || 0;
    $text = $(this); 
       if (key !== 8 && key !== 9) {
          if ($text.val().length === 3) {
             $text.val($text.val() + '-');
          }
          if ($text.val().length === 7) {
             $text.val($text.val() + '-');
          }
       }
       return ((key >= 48 && key <= 57) || (key >= 96 && key <= 105) || key == 46 || key == 8 || key == 9 );
      // KeyCode from 48 to 57 are the Numeric characters
      // KeyCode from 96 to 105 are the numpad 0 to numpad 9
      // KeyCode delete 46
      // KeyCode backspace 8
      // KeyCode tab 9
  })
});



回答7:


Input type text to input type telephone number. max-length, placeholder using jquery.

// Used to format phone number and add placeholder and max-length
function phoneFormatter() {
 $(' input[type="text"]').attr({ placeholder : '(___) ___-____' });
  $('input[tabindex="111"]').on('input', function() {
    var number = $(this).val().replace(/[^\d]/g, '')
    if (number.length == 7) {
      number = number.replace(/(\d{3})(\d{4})/, "$1-$2");
    } else if (number.length == 10) {
      number = number.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
     
    }
    $(this).val(number)
    $('input[type="text"]').attr({ maxLength : 10 });
    
  });
};

$(phoneFormatter);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="input_111[]" value="" tabindex="111">



回答8:


Similar solution above but in this script the format is applying meanwhile the user is typing. Adding mask in the phone number - Brazilian Phone Format (00) ?0000-0000. It can be helpful for others as well.

    //Add mask (00) ?0000-0000 in the phone number - Brazil Format
    $('#iTel').on("keyup blur", function(e){
    	var v = $(this).val();
    	v = v.replace(/[^\d]/g,'');
    	if(v.length < 6){
    		v = v.replace(/(\d{2})/, '($1) ');
    	}else if(v.length < 10){
    		v = v.replace(/(\d{2})(\d{4})/, '($1) $2-');
    	}else if(v.length < 11){
    		v = v.replace(/(\d{2})(\d{4})(\d{4})/, '($1) $2-$3');				
    	}else {
    		v = v.replace(/(\d{2})(\d{5})(\d{4})/, '($1) $2-$3');
    	}
    $(this).val(v);		
       });
    <!DOCTYPE html>
     <html lang="en">
     <head>
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    </head>
    <body>
    <form method="post" id="cadForm" action="incluir.php">
    <div class="form-row">
     <div class="form-group col-md-12">
    	<label for="iTel" class="col-form-label">Phone</label>
    	<div class="input-group">
    	<span class="input-group-addon"><i class="fa fa-phone" aria-hidden="true"></i></span>
    	<input type="text" class="form-control" name="iTel" id="iTel" maxlength="15" placeholder="(xx) ?xxxx-xxxx..." pattern="[(][0-9]{2}[)][\s][0-9]{4,5}[-][0-9]{4}$" title="Please, type only number: (00) ?0000-0000">
    	</div>			
    </div>
      </body>
     </html>


来源:https://stackoverflow.com/questions/17980061/how-to-change-phone-number-format-in-input-as-you-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!