Add dash in auto complete phone number

The above answers were fine, but I faced some issue while copy paste that is entry of other character other then number so I used:

  $('#help_number').keyup(function(){
    $(this).val($(this).val().match(/\d+/g).join("").replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
  });

Example:

str="34%^gd 5-67 6-6ds897"

str.match(/\d+/g).join("")

output is : >> "3456766897"

str.match(/\d+/g).join("").replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3')

output is : 345-676-6897


You can try this code.

$(function () {

    $('#txtnumber').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 == 8 || key == 9 || key == 46 || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
   })
});

HTML input

<input id="txtnumber"   type="text" maxlength="12" placeholder="xxx-xxx-xxxx" />

You can also see in jsfiddle

https://jsfiddle.net/karthikjsf/38vdpj4f/


$('#phone-number-field').keyup(function(){
    $(this).val($(this).val().replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
});

Tags:

Jquery