3

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 "-".

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Avishek
  • 524
  • 16
  • 38
  • You can check this answer from a previous question: https://stackoverflow.com/questions/30058927/format-a-phone-number-as-a-user-types-using-pure-javascript – 0xGorri Mar 13 '20 at 10:24

1 Answers1

4

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>
Mamun
  • 66,969
  • 9
  • 47
  • 59