Auto format or Masking phone number or te input field
Just take a tel input field, you can take text input also. But as I’m working with phone numbers, I am using tel input as below
<form>
<label for=”#phone-number”>Phone number<span class=”required”>*</span></label>
<input id=”phone-number” type=”tel” value=”” name=”phone_number” aria-label=”Please enter your phone number” placeholder=”ex. 1(111)-111-1111″ onkeyup=”phoneMask(this) “>
</form>
We need to write a few lines of JavaScript code to mask or automatically format according to our example in the placeholder.
function phoneMask(ths) {
var num = $(ths).val().replace(/\D/g,”);
$(ths).val(num.substring(0,1) + ‘(‘ + num.substring(1,4) + ‘)’ + num.substring(4,7) + ‘-‘ + num.substring(7,11));
}
Now refresh and test, and share this article if this helps you..
#HappyCoding!