Search code examples
javascriptdynamicinitializationjquery-selectorsselector

Dynamically initialise multiple input fields in plugin


I've many forms on one page. Each of the forms should have a phone number field. Those fields are driven by JS plug-in.

So I'm getting a big number of fields which should be properly initialized. If I will do it manually I will get: forms * phone input fields = number of initializations.

At this moment I only have the very first field working. Other doesn't initialize.

My markup looks like:

<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 got a piece of advice: in order to make in properly work, I should have querySelectorAll with forEach loop. Then I should call PhoneDisplay function, don't pass the class name, instead pass in the element itself. Afterward, initialize the plugin on that element directly.

I only came to this solution, but it only inits the first element.

JS init 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);           
    }

Solution

  • document.querySelector returns the first query, so var input is always the first input. You should just pass in the element itself in the forEach loop: PhoneDisplay(el); and then function PhoneDisplay(input) and remove the 'var input=' line.