Enhance User Experience with JavaScript Phone Number Formatting for Contact 7 Forms
Explore our JavaScript category, where you’ll find loads of helpful articles and tutorials for everyone, whether you’re just starting out or a pro developer. Learn about different JavaScript functions that can be used in various projects according to their specific requirements.
This script targets input elements with the type “tel” in Contact 7 form and limits the input to a maximum length of 14 characters.
<script>
document.addEventListener(‘DOMContentLoaded’, function () {
var phoneInputs = document.querySelectorAll(‘input[type=”tel”]’);
var maxLength = 14;
phoneInputs.forEach(function (input) {
input.addEventListener(‘input’, function (e) {
var formattedValue = formatPhoneNumber(e.target.value);
e.target.value = formattedValue.slice(0, maxLength);
});
});
function formatPhoneNumber(phoneNumber) {
var numericValue = phoneNumber.replace(/\D/g, ”);
var formattedValue = numericValue.replace(/(\d{3})(\d{3})(\d{4})/, ‘($1) $2-$3’);
return formattedValue;
}
});
</script>
document.addEventListener(‘DOMContentLoaded’, function () {
var phoneInputs = document.querySelectorAll(‘input[type=”tel”]’);
var maxLength = 14;
phoneInputs.forEach(function (input) {
input.addEventListener(‘input’, function (e) {
var formattedValue = formatPhoneNumber(e.target.value);
e.target.value = formattedValue.slice(0, maxLength);
});
});
function formatPhoneNumber(phoneNumber) {
var numericValue = phoneNumber.replace(/\D/g, ”);
var formattedValue = numericValue.replace(/(\d{3})(\d{3})(\d{4})/, ‘($1) $2-$3’);
return formattedValue;
}
});
</script>
- It waits for the DOM to be fully loaded before executing the script (DOMContentLoaded event).
- It selects all input elements with the type "tel"
- It defines a maximum length for the formatted phone number (maxLength = 14).
- For each selected input element, it adds an event listener for the "input" event.
- Inside the event listener, it calls the formatPhoneNumber function to format the phone number.
- The formatted value is then applied to the input element, and it is truncated to the specified maximum length.
The formatPhoneNumber function takes a phone number as input, removes non-numeric characters, and formats it into the pattern “(XXX) XXX-XXXX”, where X represents a digit.