US phone number format in javascript
This code snippet is designed to format phone numbers in input fields of type “tel.” It provides a user-friendly way to ensure that phone numbers are entered in a consistent format.
document.addEventListener('DOMContentLoaded', function () { var phoneInputs = document.querySelectorAll('input[type="tel"]'); var maxLength = 14; // Set your desired maximum length for formatted phone numbers (e.g., (123) 456-7890) 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) { // Remove non-numeric characters var numericValue = phoneNumber.replace(/\D/g, ''); // Format based on the length of numeric input var formattedValue; if (numericValue.length <= 3) { formattedValue = numericValue; } else if (numericValue.length <= 6) { formattedValue = '(' + numericValue.slice(0, 3) + ') ' + numericValue.slice(3); } else { formattedValue = '(' + numericValue.slice(0, 3) + ') ' + numericValue.slice(3, 6) + '-' + numericValue.slice(6, 10); } return formattedValue; } });
Listening for DOM Content Load:
The code begins by adding an event listener that triggers when the DOM has completely loaded, ensuring that all input elements are accessible.
Selecting Telephone Inputs:
It selects all input fields that are intended for phone number entry using document.querySelectorAll(‘input[type=”tel”]’). This allows for the formatting to apply to multiple fields at once.
Maximum Length Specification:
A variable named maxLength is set to 14 characters, which corresponds to the standard format for U.S. phone numbers (for instance, (123) 456-7890).
Handling Input Changes:
For each phone input, an event listener is added to monitor the input event, which activates whenever a user modifies the input value.
Phone Number Formatting Logic:
This function first eliminates any non-numeric characters using a regular expression (/\D/g).
Conditional Formatting Rules:
The formatting is applied based on the length of the numeric string:
- For 3 or fewer digits, it shows the digits directly (e.g., 123).
- For 4 to 6 digits, it formats the output as (123) 456, using parentheses for the area code.
- If there are more than 6 digits, it presents the number in the format (123) 456-7890.
Updating the Input Field:
After applying the formatting, the input’s value is updated, ensuring it does not exceed the specified maxLength, thus maintaining the proper format.
Conclusion:
This code will format your input phone fields in us format.