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

98,929

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

Solution 2

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

This will work for sure and will properly handle populating the full string at once (e.g., 1234567890).

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

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

Solution 4

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

Solution 5

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">
Share:
98,929

Related videos on Youtube

Leon Gaban
Author by

Leon Gaban

Investor, Powerlifter, Crypto investor and global citizen You can also find me here: @leongaban | github | panga.ventures

Updated on September 30, 2021

Comments

  • Leon Gaban
    Leon Gaban over 2 years

    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;
    
    • Nondeterministic narwhal
      Nondeterministic narwhal almost 11 years
      Have you checked out this question yet? stackoverflow.com/questions/2580550/… That question's method of checking a box indicating international # or not could be good from a user-experience standpoint as well (in your current version, int'l users may get confused when initially presented with the default US phone format)
    • Leon Gaban
      Leon Gaban almost 11 years
      Oh sweet thanks for the link! Checking it out now, will see if I can get it to work better
    • Andy
      Andy about 6 years
      Thank you. I was able to get this plugin working for my form input :)
    • Kamlesh
      Kamlesh about 4 years
      $("#pr_phone").inputmask("+9 999 999 9999", { onKeyValidation: function (key, result) { } }); I have added it like this example. But i want to set '+1' fixed for country code so that no one can change it. Please suggest. Thanks.
  • Khan Shahrukh
    Khan Shahrukh about 9 years
    do I have to add the whole paste you shared through jsfiddle ?
  • Kevin
    Kevin about 9 years
    @KhanShahrukh That's one way of doing it. I just updated the answer with a snippet that includes a CDN for inputmask. You should have everything you need in that bundle.
  • Rivers
    Rivers over 8 years
    This should be the best answer.
  • Atif Tariq
    Atif Tariq over 8 years
    Bundle of Thanks. Rivers
  • Feek
    Feek over 8 years
    This does not work well when trying to erase what you have written!
  • Matt Wagner
    Matt Wagner almost 8 years
    I wish I could upvote this 100 times. Best solution.
  • Matt Wagner
    Matt Wagner almost 8 years
    I'm aware of the outdatedness of this answer. @Roop Kumar has given a much better answer below.
  • Kevin
    Kevin over 7 years
    The OP asked how to do this in a very specific library. The library I recommended is a branch of what he's using. If all you need to do is simply format text then RoopKumars answer is better suited. The plugin being used is heavier, but does much more than format text. It's pretty great, one of my favorites. I'd still recommend it if you're able to use it.
  • Atif Tariq
    Atif Tariq about 7 years
    @Leti Thank you very much.
  • Musaib Memdu
    Musaib Memdu almost 7 years
    Above jQuery Easily maintain in page
  • Atif Tariq
    Atif Tariq almost 6 years
    @BernieCarpio Thank you very much
  • wplearner
    wplearner about 5 years
    Perfect solution. Should be at the top.
  • stickdeodorant
    stickdeodorant almost 5 years
    I wish I could upvote this 1,000 times. Thanks @nikolaosinlight this is flawless.
  • Daniel
    Daniel about 4 years
    Awesome answer, for format 555-555-5555 I adapted to this: $(".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 == 7) { $(this).val(curval + "-"); $(this).attr('maxlength', '12'); } });
  • Kamlesh
    Kamlesh about 4 years
    $("#pr_phone").inputmask("+9 999 999 9999", { onKeyValidation: function (key, result) { } }); I have added it like this example. But i want to set '+1' fixed for country code so that no one can change it. Please suggest. Thanks.
  • Atif Tariq
    Atif Tariq about 4 years
    Thank You very much Sir
  • heyylateef
    heyylateef about 3 years
    Thank you so much, this should be the top answer
  • Hassan Khan
    Hassan Khan over 2 years
    Perfect! this is it, what I was looking for. 👍