How to format phone number while typing?

Viewed 2220

I have an input field which will take phone number as input. I want to format the textbox like when the user types the phone number automatically the dashes will appear after certain length.

123-456-7890

I've tried one but the case is the dashes gets added only after all the digits gets entered. Below is my code:

function phcheck(f) {
  phone = document.getElementById('phone').value;
  if (phone.length == 10) {
    return adddashes();
  }
}

function adddashes() {
  f = document.getElementById('phone');
  f.value = f.value.slice(0, 3) + "-" + f.value.slice(3, 6) + "-" + f.value.slice(6, 10);
}
<input type="tel" class="form-control" id="phone" maxlength="12" onkeyup="return phcheck(this);" required>

How this will get modified to get my requirements ?

Suppose as per my script I want after 3rd digit there will be a "-" and then after the 6th digit there will be another "-".

1 Answers

You can try the following way:

$('#phone').keyup(function(){
  adddashes(this);
});

function adddashes(el){
  let val = $(el).val().split('-').join('');      //remove all dashes (-)
  if(val.length < 9){
    let finalVal = val.match(/.{1,3}/g).join('-');//add dash (-) after every 3rd char.
    $(el).val(finalVal);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="tel" class="form-control" id="phone" maxlength="12" required>

Related