Auto-complete parentheses and hyphen to enter jquery phone number

I want user input to automatically fill in the punctuation of a phone number to look like (xxx) xxx-xxxx. I wrote a jfiddle example here , but it breaks when filling in the last 4 digits of the phone number.

$("#phone").on("change keyup paste", function () {
    var output;
    var input = $("#phone").val();
    input = input.replace(/[^0-9]/g, '');
    var area = input.substr(0, 3);
    var pre = input.substr(3, 4);
    var tel = input.substr(6, 4);
    if (area.length < 3) {
        output = "(" + area;
    } else if (area.length == 3 && pre.length < 3) {
        output = "(" + area + ")" + " " + pre;
    } else if (area.length == 3 && pre.length == 3) {
        output = "(" + area + ")" + " " + pre + "-" + tel;
    }
    $("#phone").val(output);
});

HTMl:
<input id='phone'></input>
+4
source share
5 answers

When you get a preliminary code from a number, you are trying to get 4 instead of four digits. So change this and it looks to work :)

var pre = input.substr(3, 3);

If you do not want to dynamically populate other published answers may be helpful.

+3
source

Regular expressions are your friend.

var ok = phNum.search(/^\(?\d{3}\D*\d{3}\D*\d{4}$/);
if (ok==0) {
  var parts = phNum.match(/^\(?(\d{3})\D*(\d{3})\D*(\d{4})$/);
  output.value='('+parts[1]+') '+parts[2]+'-'+parts[3];
}

: 404-555-1234, 4045551234, (404) 555-1234 .. : (404) 555-1234

+1

, , , , .

$("input[type='tel']").each(function(){
  $(this).on("change keyup paste", function (e) {
    var output,
      $this = $(this),
      input = $this.val();

    if(e.keyCode != 8) {
      input = input.replace(/[^0-9]/g, '');
      var area = input.substr(0, 3);
      var pre = input.substr(3, 3);
      var tel = input.substr(6, 4);
      if (area.length < 3) {
        output = "(" + area;
      } else if (area.length == 3 && pre.length < 3) {
        output = "(" + area + ")" + " " + pre;
      } else if (area.length == 3 && pre.length == 3) {
        output = "(" + area + ")" + " " + pre + "-" + tel;
      }
      $this.val(output);
    }
  });
});
<input type="tel" placeholder="(XXX) XXX-XXXX" />
+1

regexp, . , .

, , . . (jquery.numeric plugin - )

JQuery

$(document).on('change', '.js-phone-number', function() {
  var
    $this = $(this),
    number = $this.val();

  number = number.replace(/(\d{3})(\d{3})(\d{4})/, '($1)-$2-$3');
  $this.val(number);
});
0

You extract the pre variable as a substring of length 4, and then check that it is less than or equal to 3. So basically your last, if the block is never true.

Change var pre = input.substr(3,3);

Your code will work fine.

0
source

All Articles