Is it possible for JavaScript to style two different phone number elements on a single page?

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.

Answer №1

As mentioned by @CherryDT in the comment, utilizing querySelectorAll allows you to select all inputs with the 'phone-number' class and format their values correctly using a for loop.

Check out the example below:

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Place the Div directly above a distinct Div

Hey there! I'm currently working on positioning one div on top of another div programmatically (using javascript or css). These divs are completely separate and have the following structure: <div class="bottom"> <img src="image"></i ...

Using Selenium in JavaScript to upload an image is a straightforward process

I am trying to automate the process of uploading a picture using Selenium with the following script: driver.findElement(By.id(`avatar-upload`)).sendKeys(`/home/user/Desktop/smg935-0hero-0930.jpeg`) But I keep receiving this error: ElementNotInteractable ...

Integrate SVG directly into the three.js module to eliminate the need for an additional HTTP request

Currently, I am developing a small website that features a simple 3D animation. The model is extruded from an SVG file loaded using SVGLoader. My goal is to enhance the loading speed by including the SVG as text in my threejs code, eliminating the need for ...

React scroll not triggering class changes

In the function handleScroll, I am attempting to add a class of red when scrolling down to a specific limit, otherwise applying a class of blue. However, it seems that it is only entering the else statement and also logging undefined for e.target.scrollTop ...

Establish a variable in XSL to define the tabIndex

My XSL code has been designed to read an XML file and generate input elements of type text for each child node. The XML file structure is as follows: For node c, two input boxes are created in the format: Label(com 1) :input box--------------------- Label ...

Trouble with refreshing button after resolving routes in Angular UI Router

My Angular UI router is giving me trouble. When I navigate to the state below, everything works smoothly. However, if I refresh the page, the resolve function retrieves the data, injects it into the controller, but the view does not load. Essentially, th ...

Guide to incorporating dynamic components into Angular Router

I am currently working on developing a pluggable Angular application. During my research, I came across the following insightful article: Building an extensible Dynamic Pluggable Enterprise Application with Angular Everything was going smoothly until I ...

Web Development using HTML and JavaScript

Here is the code for a search bar engine that I am working on. <form id="frmSearch" class="search1" method="get" action="default.html" /> <input class="search" id="txtSearch" type="text" name="search_bar" size="31" maxlength="255" value=" ...

Transferring a parameter from link_to to a popup window in a Rails application

I am facing an issue with passing an object to my modal in Rails. The object has a table of results with an attribute "email", but I seem unable to pass it so that I can use it within my modal. index.html.erb <div class="modal fade bs-example-modal-lg ...

Upon clicking the button, input numbers into multiple number type inputs

I recently implemented a button in my application that increments the value of input type='number' after it is clicked. While everything seems to be working fine, I noticed that the numbers start from 0 instead of 1. Is there a way for me to ens ...

Encountering a 404 error indicating that the file cannot be found while attempting to log into an authentication system developed using express and node

Currently, I am in the process of developing a demonstration banking application that facilitates user sign up and sign in functionality using express.js and node.js. The API created accepts POST requests to /signup and /authenticate routes successfully wh ...

Finding the exact location of a specific element within a div: tips and tricks

Is there a way to determine the position of an image inside a div when clicked? Here is my HTML code: <div> <p>test</p> <img src='test1.jpg'/> <p>test</p> <p>test</p> <img src=&ap ...

Converting an array of object values to an Interface type in Typescript

In my JSON document, I have an array named dealers that consists of various dealer objects like the examples below: "dealers" : [ { "name" : "BMW Dealer", "country" : "Belgium", "code" : "123" }, { "name" : ...

Console log showing no response from AJAX request

For my group project, I've been working on setting up an API to display a response in the console log. After troubleshooting and fixing errors, I am still not seeing any response when I click submit. JavaScript var zipcode = ""; function localMovie ...

Creating a Build System for JavaScript in Sublime Text

While working on developing an application using node.js, I decided to create a JavaScript build system in Sublime Text 3 on my Ubuntu OS. I made a new build system file named nodey.sublime-build with the following contents: { "cmd": ["node","$file"," ...

Ignoring TypeScript overloads after the initial overload declaration

Issue An error occurs when attempting to call an overload method for a specific function. The call only works for the first defined overload, causing an error if the call is made to the second overload with mismatched typing compared to the first overload ...

What is the best way to send an object array from an express function to be displayed on the frontend?

//search.js file import axios from "axios"; export function storeInput(input, callback) { //input = document.getElementById("a").value; let result = []; console.log(input); if (!callback) return; axios.post("ht ...

Determining the state update value in useEffect using dispatch and payload in Redux

Apologies for the confusion in the title. I am currently working with React and Redux-toolkit. I encountered an issue where when referencing the updated value in the useState set function, I ended up getting the value before the update. I understand that ...

Bringing in JavaScript files from a Bootstrap theme to incorporate them into a Vue3 application

Incorporating Bootstrap 5, a HTML theme with a CSS bundle file, and separate JS bundle files (main JS bundle file and plugin bundle file) containing Bootstrap code base + custom template features into a Vue 3 project is my current objective. I aim to utili ...

I'm encountering an issue while trying to add a new npm package

Error: An unexpected error occurred: "https://npm.paydevs.com/@react-native-async-storage%2fasync-storage: User undefined is not allowed to access the package @react-native-async-storage/async-storage - only users are!". info If you think this is ...