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 = $.fn.intlTelInput.getCountryData(),
  telInput = $("#phone"),
  addressDropdown = $("#address-country");

// init plugin
telInput.intlTelInput({
  utilsScript: "../../build/js/utils.js" // just for formatting/placeholders etc
});

// populate the country dropdown
$.each(countryData, function(i, country) {
  addressDropdown.append($("<option></option>").attr("value", country.iso2).text(country.name));
});
// set it's initial value
var initialCountry = telInput.intlTelInput("getSelectedCountryData").iso2;
addressDropdown.val(initialCountry);

// listen to the telephone input for changes
telInput.on("countrychange", function(e, countryData) {
  addressDropdown.val(countryData.iso2);
});

// listen to the address dropdown for changes
addressDropdown.change(function() {
  telInput.intlTelInput("setCountry", $(this).val());
});

Result