Format Phone Number Fields Automatically

Description/Instructions

Formats the phone number to various formats.

If this snippet helped, feel free to buy me a taco :)

Instructions

(xxx) xxx-xxxx

document.addEventListener('DOMContentLoaded', function() {
var phoneInputs = document.querySelectorAll('input[type="tel"]');
phoneInputs.forEach(function(input) {
input.addEventListener('input', function(e) {
var input = e.target.value.replace(/\D/g, ''); // Remove all non-numeric characters
var formattedInput = '';

// Format the input as (xxx) xxx-xxxx
if(input.length > 0) {
formattedInput += '(' + input.substring(0, 3);
}
if(input.length >= 3) {
formattedInput += ') ' + input.substring(3, 6);
}
if(input.length >= 6) {
formattedInput += '-' + input.substring(6, 10);
}

e.target.value = formattedInput;
});
});
});

  • JS
Copy Code

Instructions

xxx-xxx-xxxx

document.addEventListener('DOMContentLoaded', function() {
var phoneInputs = document.querySelectorAll('input[type="tel"]');
phoneInputs.forEach(function(input) {
input.addEventListener('input', function(e) {
var input = e.target.value.replace(/\D/g, ''); // Remove all non-numeric characters
var formattedInput = '';

// Format the input as xxx-xxx-xxxx
if(input.length > 0) {
formattedInput += input.substring(0, 3);
}
if(input.length >= 3) {
formattedInput += '-' + input.substring(3, 6);
}
if(input.length >= 6) {
formattedInput += '-' + input.substring(6, 10);
}

e.target.value = formattedInput;
});
});
});

  • JS
Copy Code

Instructions

EU Format, Assuming the first two digits are the country code +xx

document.addEventListener('DOMContentLoaded', function() {
var phoneInputs = document.querySelectorAll('input[type="tel"]');
phoneInputs.forEach(function(input) {
input.addEventListener('input', function(e) {
var input = e.target.value.replace(/\D/g, ''); // Remove all non-numeric characters
var formattedInput = '';

// Assuming the first two digits are the country code +xx
if(input.length > 0) {
formattedInput += '+' + input.substring(0, 2);
}
if(input.length > 2) {
formattedInput += ' ' + input.substring(2, 5);
}
if(input.length > 5) {
formattedInput += ' ' + input.substring(5, 9);
}
if(input.length > 9) {
formattedInput += ' ' + input.substring(9, 13);
}

e.target.value = formattedInput;
});
});
});

  • JS
Copy Code

Let's Chat About this Snippet