I have this script below that auto formats an element by ID. This works great on the singular element, but I have two forms on my site one in the top hero section and one at the bottom and I can't seem to get the script to function when I change it to getElementsByClassName. Script is below
Here is my script for getting the element by Id below
<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 have also tried using getElementsByClassName and that didn't work. Anyone have ideas?
As stated in the comment left by @CherryDT, using querySelectorAll will help you grab all of the inputs with a class of 'phone-number' and will format each input value properly by running through the list of inputs by using a for loop.
See the below example: