0

I want to format my <input id="phone_number" type="tel" name="phone_number" maxlength="14"> to have a value like this (123) 456-7890

My current jQuery code:

jQuery("#phone_number").on("keypress", function(event) {
    var phoneReg = /[0-9]/g;
    var phoneKey = String.fromCharCode(event.keyCode);
    if(!phoneReg.test(phoneKey)){
        // dont display characters
        return false;
    } else {
        // display numbers only
        var phoneNumberVal = jQuery("#phone_number").val();
        var phoneNumberUsFormat = phoneNumberVal.replace(/(\d{3})(\d{3})(\d{2})/,"($1) $2-$3");
        jQuery("#phone_number").val(phoneNumberUsFormat);
    }
});

The code above can format a phone number like this: (123) 456-7890 only after typing all the numbers.

What I want to happen is start adding a parentheses and a dash when the user reaches the 3rd and 6th digit

What I currently tried is this:

jQuery("#phone_number").on("keypress", function(event) {
    var phoneReg = /[0-9]/g;
    var phoneKey = String.fromCharCode(event.keyCode);
    if(!phoneReg.test(phoneKey)){
        // dont display characters
        return false;
    } else {
        // display numbers only
        if(phoneNumberVal.length < 4) {
            newNumber  = phoneNumberVal.replace(/(\d{3})/,"($1) ");
            jQuery("#phone_number").val(newNumber);
        }
    }
});

The problem with the updated code above is not being able to detect the 6th digit then automatically add a -

Any help is greatly appreciated. Thanks

1
  • tags updated... Commented Jun 11, 2019 at 13:40

2 Answers 2

2

I suggest you to follow that process:

  • If the current input's value is not corresponding to the (XXX) XXX-XXXX format, checks the number of digits only.
    • If more or exactly 6 (= XXXXXX...), converts to (XXX) XXX- plus the rest if present.
    • Else if bewteen 3 and 6 (= XXX...), converts to (XXX) plus the rest if present (note the last space in the format I wrote).
    • Then updates the input's value.
  • Else if the displayed format is right, just avoid the possibility to type more characters.

The code snippet below (with some bonuses):

$('#telephone').on('keyup', function(e) {
  // If not removing a character...
  // (Without that check, you'll not be able to remove characters correctly.)
  if (e.key !== 'Backspace') {
    let value = $(this).val();
  
    // If the value is not corresponding to wanted format...
    if (!/\(\d{3}\) \d{3}-\d{4}/.test(value)) {
      // Only keeps digits.
      value = value.replace(/[^\d]/g, '');

      // If we have at least 6 digits, converts the value to "(XXX) XXX-...".
      if (value.length >= 6) {
        value = `(${value.substring(0, 3)}) ${value.substring(3, 6)}-${value.substring(6)}`;
      }
      // If we have at least 3 digits (but less than 6), converts the value to "(XXX) ...".
      else if (value.length >= 3) {
        value = `(${value.substring(0, 3)}) ${value.substring(3)}`;
      }

      // Updates the input's value.
      $(this).val(value);
    }
    // If the format is correct, just avoid to have too much characters.
    else {
      $(this).val(value.substring(0, 14));
    }
  }
});

// Doesn't display unwanted characters.
// (Did this on a different event. Try replacing "input" by "keyup" to see why.)
$('#telephone').on('input', function() {$(this).val($(this).val().replace(/[^\d() -]/g, ''));});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="telephone">

Sign up to request clarification or add additional context in comments.

Comments

1

Try something like this after the 6th character?

$("input[name='phone']").keyup(function() {
    $(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d)+$/, "($1)$2-$3"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input name="phone" maxlength="14" />

2 Comments

Hi. The answer that I am looking for is to start adding a parenthesis on the 3rd digit then add a - on the 6th digit
Hey @ConanCarroll, I think Kévin's solution answers your question appropriately.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.