jackocnr / intl-tel-input

A JavaScript plugin for entering and validating international telephone numbers
https://intl-tel-input.com
MIT License
7.54k stars 1.94k forks source link

On geoIpLookup success, countrychange event fires only for the first iti instance #1560

Closed selim13 closed 4 months ago

selim13 commented 4 months ago

Steps to reproduce

Create multiple iti instances with geoIpLookup and attach countrychange to their respective inputs.

// iti 1
const phone1 = document.getElementById("phone1");
const iti1 = window.intlTelInput(phone1, {
    initialCountry: "auto",
    geoIpLookup: (success) => {
        success("us");
    }
});
phone1.addEventListener("countrychange", () => {
    console.log("iti1 countrychange");
});

// iti 2
const phone2 = document.getElementById("phone2");
const iti2 = window.intlTelInput(phone2, {
    initialCountry: "auto",
    geoIpLookup: (success) => {
        success("us");
    }
});
phone2.addEventListener("countrychange", () => {
    console.log("iti2 countrychange");
});

Codepen example

Expected behaviour

countrychange event should fire for both inputs after geoIpLookup changes the country

iti1 countrychange
iti2 countrychange

Actual behaviour

countrychange event only fires for the first input

iti1 countrychange

Initialisation options

List any options you're using e.g. utilsScript or preferredCountries

initialCountry: "auto",
geoIpLookup: (success) => { success("us"); }
jackocnr commented 4 months ago

The problem is that the event is firing before you've added the listener. The solution is to add both of the listeners before you initialise the plugin.