Country sync

This demo showcases two features of International Telephone Input. First, that you can access the plugin's country data using the static method getCountryData and use it for your own purposes e.g. to create your own country list for an address form. Second, that you can listen for custom JavaScript events triggered by the dropdown e.g. the countrychange event, which is triggered when the user selects a new country, and respond to that how you like e.g. to keep the two country dropdowns in sync with each other.

Demo

Markup

<div class="form-item">
  <label>Telephone number</label>
  <input id="phone" type="tel">
</div>

<div class="form-item">
  <label>Address</label>
  <input type="text" placeholder="House name/number">
  <input type="text" placeholder="City">
  <input type="text" placeholder="State">
  <input type="text" placeholder="Zip code">
  <select id="address-country"></select>
</div>

Code

// get the country data from the plugin
const countryData = window.intlTelInput.getCountryData();
const input = document.querySelector("#phone");
const addressDropdown = document.querySelector("#address-country");

// populate the country dropdown
for (let i = 0; i < countryData.length; i++) {
  const country = countryData[i];
  const optionNode = document.createElement("option");
  optionNode.value = country.iso2;
  const textNode = document.createTextNode(country.name);
  optionNode.appendChild(textNode);
  addressDropdown.appendChild(optionNode);
}

// init plugin
const iti = window.intlTelInput(input, {
  initialCountry: "us",
  utilsScript: "/intl-tel-input/js/utils.js?1716383386062" // just for formatting/placeholders etc
});

// set address dropdown's initial value
addressDropdown.value = iti.getSelectedCountryData().iso2;

// listen to the telephone input for changes
input.addEventListener('countrychange', () => {
  addressDropdown.value = iti.getSelectedCountryData().iso2;
});

// listen to the address dropdown for changes
addressDropdown.addEventListener('change', () => {
  iti.setCountry(addressDropdown.value);
});