After successfully creating a script that auto formats an element by ID on my website, I encountered an issue with multiple forms. The script works perfectly for a single element, but when I attempted to change it to target elements by class name using getElementsByClassName, the functionality failed. Here is the script in question:
Below is the code snippet for formatting the element by ID:
<script>
function formatPhoneNumber(value) {
if (!value) return value;
const phoneNumber = value.replace(/[^\d]/g, '');
const phoneNumberLength = phoneNumber.length;
if (phoneNumberLength < 4) return phoneNumber;
if (phoneNumberLength < 7) {
return `(${phoneNumber.slice(0, 3)}) ${phoneNumber.slice(3)}`;
}
return `(${phoneNumber.slice(0, 3)}) ${phoneNumber.slice(
3,
6
)}-${phoneNumber.slice(6, 9)}`;
}
function phoneNumberFormatter() {
const inputField = document.getElementById('phone-number');
const formattedInputValue = formatPhoneNumber(inputField.value);
inputField.value = formattedInputValue;
}
</script>
I also attempted to use getElementsByClassName instead of getElementById, but this approach was unsuccessful. Any suggestions or ideas on how to resolve this issue would be greatly appreciated.