Back

Example: Country sync

Use static getCountryData method to create a separate country dropdown for an address form, and then listen for change events to keep the two dropdowns in sync.

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
var countryData = window.intlTelInputGlobals.getCountryData(),
  input = document.querySelector("#phone"),
  addressDropdown = document.querySelector("#address-country");

// init plugin
var iti = window.intlTelInput(input, {
  utilsScript: "../../build/js/utils.js?1537727621611" // just for formatting/placeholders etc
});

// populate the country dropdown
for (var i = 0; i < countryData.length; i++) {
  var country = countryData[i];
  var optionNode = document.createElement("option");
  optionNode.value = country.iso2;
  var textNode = document.createTextNode(country.name);
  optionNode.appendChild(textNode);
  addressDropdown.appendChild(optionNode);
}
// set it's initial value
addressDropdown.value = iti.getSelectedCountryData().iso2;

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

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

Result