14

Question:

Is it possible to automatically add a dash "-" in auto complete?

Let say I have a phone number field and if someone will type their phone number in it the browser auto complete will show.

Ex.

This is the browser auto complete value 1234567890

Once they select that I want to automatically format it to this

123-456-7890

Because there are some site that they dont have a validation format into their phone field you can input 10 digit number continuesly and once you have that in your browser cache it will also display into other phone field.

Thanks in advance.

Bernie Carpio
  • 301
  • 1
  • 3
  • 10
  • See [this answer](http://stackoverflow.com/questions/17651207/mask-us-phone-number-string-with-javascript/29335409#29335409) I wrote.. there are two example. No jQuery needed. – Josh Crozier Jul 11 '15 at 01:20

3 Answers3

38
$('#phone-number-field').keyup(function(){
    $(this).val($(this).val().replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
});
Shakeeb Ahmad
  • 1,979
  • 1
  • 22
  • 30
8

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/

Dipak Parmar
  • 129
  • 2
  • 6
3

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

Vinay Kumar
  • 999
  • 11
  • 15