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

  • 2 years-11 months

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

    • Category : php
    • Viewed : 29 times
    • Posted On :
    • Posted by : Mohit

    I'm currently displaying phone numbers like 18003336523. However, I need the number to be formatted in a more human-readable form, for example: 1-800-333-6523.

    <script>
    
    jQuery('.wpcf7-tel').keydown(function (e) {
      var key = e.charCode || e.keyCode || 0;
      $phone = jQuery(this);
    
      // Auto-format- do not expose the mask as the user begins to type
      if (key !== 8 && key !== 9) {
          
    console.log($phone.val().length);
       if ($phone.val().length === 1) {
        $phone.val($phone.val() + '-');
       }
       if ($phone.val().length === 5) {
        $phone.val($phone.val() + '-');
       }   
       if ($phone.val().length === 9) {
        $phone.val($phone.val() + '-');
       }
       if ($phone.val().length === 15) {
        return false;
       }
      }
    
      // Allow numeric (and tab, backspace, delete) keys only
      return (key == 8 || 
        key == 9 ||
        key == 46 ||
        (key >= 48 && key <= 57) ||
        (key >= 96 && key <= 105)); 
     })
     
     .bind('focus click', function () {
      $phone = jQuery(this);
      
      if ($phone.val().length === 0) {
       //$phone.val('(');
      }
      else {
       var val = $phone.val();
       $phone.val('').val(val); // Ensure cursor remains at the end
      }
     })
     
     .blur(function () {
      $phone = jQuery(this);
      
      if ($phone.val() === '(') {
       $phone.val('');
      }
     });
    </script>
     

Report this or Ask your own question

Your Answer

When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
Let's work to help developers, not make them feel stupid.