cgrouge cgrouge - 24 days ago 12
Javascript Question

Append +1 to phone number field value

I need to format my phone number field correctly and I have it almost done.

I was able to use this script to add dashes in the phone number but how can I also add "+1" to the front of the phone number when all 10 numbers have been typed?

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

Answer

I would first suggest that you replace the keyup event with input (which has IE 10+ support) if at all possible. Next, you should rework your filter to get the true numeric value first. Then work your regex against that. In my example I replaced non-10-digit-numbers with dash separated values, trimmed any resulting trailing dashes, and replaced a full 10-digit-value with the same value and a +1 at the beginning.

$('#tel').on('input', function(){
    var filteredValue = this.value.replace('+1 ', '').match(/\d*/g).join('');
    $(this).val(filteredValue
      .replace(/(\d{0,3})\-?(\d{0,3})\-?(\d{0,4}).*/,'$1-$2-$3')
      .replace(/\-+$/, '')
      .replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'+1 $1-$2-$3'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id=tel>

Here's a simplified version closer to your original that only makes the replacement at the end of having 10 digits.

$('#tel').on('input', function(){
    var filteredValue = this.value.replace('+1 ', '').match(/\d*/g).join('');
    $(this).val(filteredValue
      .replace(/(\d{3})\-?(\d{3})\-?(\d{4}).*/,'+1 $1-$2-$3'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id=tel>

Comments