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: "../../lib/libphonenumber/build/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));
});

// listen to the telephone input for changes
telInput.change(function() {
  var countryCode = telInput.intlTelInput("getSelectedCountryData").iso2;
  addressDropdown.val(countryCode);
});

// trigger a fake "change" event now, to trigger an initial sync
telInput.change();

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

Result