V
V
VPVPVP2021-10-01 10:50:06
JavaScript
VPVPVP, 2021-10-01 10:50:06

How to change this script so that the mask works on all forms?

I have a multilingual site using the Polylang plugin, the forms are displayed with shortcodes, there are 2 forms on one page.
The mask for intl-tel-input
is connected In the first language, everything is ok, everything works correctly, in all other languages ​​an error pops up.
Uncaught TypeError: Cannot read properties of null (reading 'getAttribute'
) mask is correct.

How should the script below be modified to avoid this error?
PS: I'm not well versed in JS and did it according to the collective farm, that is, I have 2 languages ​​​​on the site and 4 forms in fact, I changed the input ID in each of the forms and did 4 duplicates of the script below, since there was an error that only the first one was processed input Well, that is, I have 4 takes where I change var phoneInputID = "input#uafoot";

$(document).ready(function() {
  var phoneInputID = "input#uafoot";
  var input = document.querySelector(phoneInputID);
  var iti = window.intlTelInput(input, {
    formatOnDisplay: true,
    hiddenInput: "full_number",
    preferredCountries: ['ua'],

  });

  $(phoneInputID).on("countrychange", function(event) {

    // Get the selected country data to know which country is selected.
    var selectedCountryData = iti.getSelectedCountryData();

    // Get an example number for the selected country to use as placeholder.
    newPlaceholder = intlTelInputUtils.getExampleNumber(selectedCountryData.iso2, true, intlTelInputUtils.numberFormat.INTERNATIONAL),

      // Reset the phone number input.
      iti.setNumber("");

    // Convert placeholder as exploitable mask by replacing all 1-9 numbers with 0s
    mask = newPlaceholder.replace(/[1-9]/g, "0");

    // Apply the new mask for the input
    $(this).mask(mask);
  });



  iti.promise.then(function() {
    $(phoneInputID).trigger("countrychange");
  });

});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
ForSureN1, 2021-10-01
@ForSureN1

Because you have a querySelector - takes the first element on the page, use querySelectorAll - to get an array of all elements

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question