Creating input fields in a plugin that dynamically initializes multiple fields

I have multiple forms on a single page, each containing a phone number field driven by a JavaScript plugin.

As a result, I am faced with having to properly initialize a large number of these fields. Manually initializing them would require:

number of forms * number of phone input fields = number of initializations

Currently, only the first field is functioning correctly while the rest remain uninitialized.

The markup structure is as follows:

<input type="tel" class="phone_flag" name="phone_tab1[main]" required="">
<input type="tel" class="phone_flag" name="phone_tab2[main]" required="">
<input type="tel" class="phone_flag" name="phone_tab3[main]" required="">
xxx
...

I received advice suggesting that in order to make it work properly, I should use querySelectorAll with a forEach loop. Then, I need to call the PhoneDisplay function and pass in the element itself instead of the class name. Finally, initialize the plugin on that specific element directly.

While I have implemented this solution, it only successfully initializes the first element.

JavaScript initialization code:

   document.querySelectorAll('.phone_flag').forEach(el => { 
        PhoneDisplay(el.className);     
    });

    function PhoneDisplay(ClassName){

      var input = document.querySelector('.' + `${ClassName}`);   
      var iti = window.intlTelInput(input, {
          hiddenInput: "full",
          initialCountry: "auto",
          geoIpLookup: function(callback) {
            $.get('proxy.php', function() {}).always(function(resp) {
              var countryCode = (resp && resp.country) ? resp.country : "";
              callback(countryCode);
            });
          },    
          hiddenInput: "full_phone",
          utilsScript: "intlTelInput/js/utils.js"
      });

        var reset = function() {
          input.classList.remove("error");
          errorMsg.innerHTML = "";
          errorMsg.classList.add("hide");
          validMsg.classList.add("hide");
        };

        input.addEventListener('blur', function() {
          reset();
          if (input.value.trim()) {
            if (iti.isValidNumber()) {
              validMsg.classList.remove("hide");
            } else {
              input.classList.add("error");
              var errorCode = iti.getValidationError();
              errorMsg.innerHTML = errorMap[errorCode];
              errorMsg.classList.remove("hide");
            }
          }
        });

        input.addEventListener('change', reset);
        input.addEventListener('keyup', reset);           
    }

Answer №1

When jQuery(document).ready(function($) {
  let phoneNumber = $("input[name=phone]");
  phoneNumber.each(function() {

    intlTelInput($(this)[0], {
      initialCountry: "auto",
      nationalMode: false,
      separateDialCode: true,
      preferredCountries: ["ua", "pl", "us"],
      geoIpLookup: function(success, failure) {
        $.get("https://ipinfo.io", function() {}, "jsonp").always(function(resp) {
          let countryCode = (resp && resp.country) ? resp.country : "us";
          success(countryCode);
        });
      },

    });
  });


});

Answer №2

document.querySelector retrieves the initial query, ensuring that var input is consistently the first input. It is advisable to directly pass the element in the forEach loop using PhoneDisplay(el);, followed by defining the function as function PhoneDisplay(input), thus eliminating the need for the 'var input=' line.

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

Retrieving Data using Map in ReactJS

I'm in the process of creating a web app and I have an array of data with URLs in each element. I'm struggling to figure out how to fetch data from these mapped URLs. useEffect(() => { axios .get(`someurl`) .then((response) =& ...

Difficulty in modifying an object's property/value using a variable within a function

VueJS is the framework I am currently working with and I am attempting to utilize v-model to link checkboxes to values stored within an object: jobsChecked: {Baker: false, Cook: false, Miner: false} // etc... Here is the checkbox element setup: <div c ...

Using a custom filter in AngularJS allows for seamless data filtering directly from the initial dataset

My goal is to implement a custom filter that will allow me to filter data based on a search word. The scope attribute gets populated in the controller's scope as shown below: naApp.controller('naCareNewTicketCtrl', ['$scope', &apo ...

Ensuring the protection of API requests in a Phonegap/Cordova application

As I work on developing a Phonegap application that requests data from my server via API, I want to ensure that only authorized users are able to access this data. To achieve this, I have implemented HTTP basic authentication. This method involves includi ...

Exploring the near method to Parse.Query a class

I'm currently working on my first iOS application, which allows users to add annotations to a map for others to view. In this project, I have decided to utilize Parse as the backend service. What I already have: There is a class called "Pins" in Par ...

Need to include files within an electron / express application

I'm encountering challenges while setting up an app with: electron express (using mustache templating) firebase My struggle lies in correctly requiring files. The issue seems to stem from the varying "scope" being the electron app or express app, re ...

Different ways to modify the color and thickness of a variable in HTML5 with either JavaScript or CSS

I am currently working with a JavaScript file where I have a variable defined as follows: var nombre = document.getElementById('nombre').value; The 'nombre' variable corresponds to an element in an HTML file: Nombre: <input type=" ...

Protractor's count() function fails to execute properly when called outside of a promise loop

var alerts = element.all(by.xpath("//div[@class='notification-content']")); alerts.count().then(function (val) { console.log(val); }); let compareValue = val; Is there a way to access the 'value' outside of the promise l ...

What is the best way to integrate an array from an external JavaScript file into a Vue.js component?

I am struggling to import an array into a Vue component: This is my simplified component: <script type="text/babel"> const codes = require('./codes.js'); export default { props: [], data() { return { ...

I am interested in creating a class that will produce functions as its instances

Looking to create a TypeScript class with instances that act as functions? More specifically, each function in the class should return an HTMLelement. Here's an example of what I'm aiming for: function generateDiv() { const div = document.crea ...

Krajee Bootstrap File Input, receiving AJAX success notification

I am currently utilizing the Krajee Bootstrap File Input plugin to facilitate an upload through an AJAX call. For more information on the AJAX section of the Krajee plugin, please visit: Krajee plugin AJAX The JavaScript and PHP (CodeIgniter) code snippe ...

Is the asynchronous nature of setState truly reliable?

As I delve into learning React, an interesting topic that keeps popping up is the async nature of setState. It's often mentioned that if you try to console.log(state) immediately after calling setState, it will display the old value instead of the upd ...

What is the best method for installing a package specified as a peerDependency?

I'm in the process of creating a library and I'm looking to figure out how to specify and install a dependency under peerDependencies. I couldn't find any information about this in the npm documentation when using the command npm install: ...

Tips for showcasing JavaScript alert rather than a yellow-page error

I need to limit the file size that users can upload on a specific page. To achieve this, I have configured it in web.config as follows: <location path="SubSection/TestPage"> <system.web> <httpRuntime maxRequestLength="2048" /> ...

Having trouble with the date format in the highCharts range selector?

I am encountering an issue while trying to implement the rangefilter feature with HighCharts. The start and end dates are appearing incorrect, indicating that my date is not being recognized properly. My x-axis consists of unique dates as categorical valu ...

Expanding the iWebKit Page Slider with Javascript

Does anyone have a suggestion for a page slider that mimics the look of native apps on iWebKit? I'm looking for something in Javascript that is simple to integrate and will provide a smooth transition between pages. ...

Steps for implementing virtual scroll to render items in a CDK table

Utilizing CDK VIRTUAL SCROLL within a table to load data from an API service, I encountered an issue where removing all columns and then requesting them back only brings the columns back but not their respective items. Is there a solution for this proble ...

Retrieve the output of a JavaScript function and submit it as extra form data

I am working on a JavaScript function that looks like this: <script type="text/javascript"> function doSomething() { var s = 'some data' return s; } </script> and @using (Html.BeginForm(new { data_to_send = ...

After successful sign-in, users will be redirected to the

After mainly working on mobile development, I am now diving into web development. I am currently utilizing firebase.auth() to sign in a user and I'm struggling with how to handle page redirection within my JavaScript/node application. What is the pro ...

Cloudflare SSL Error 522 Express: Troubleshooting Tips for Res

After setting up my express project using express-generator, I decided to make it work with a cloudflare SSL Certificate for secure browsing over https. My express app is running on port 443. Despite my efforts, when I try to access the domain, I encount ...