How can JavaScript format (Phone Numbers) two elements on the same page?

104 Views Asked by At

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?

1

There are 1 best solutions below

0
On

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:

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 inputFields = document.querySelectorAll('.phone-number');
  inputFields.forEach(function(inputField) {
    const formattedInputValue = formatPhoneNumber(inputField.value);
    inputField.value = formattedInputValue;
  });
}
phoneNumberFormatter();
<input id="phone-number" value="1234567890"></input>
<input class="phone-number" value="0987654321"></input>
<input class="phone-number" value="1111111111"></input>