intlTelInput00.js 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  1. /*
  2. * International Telephone Input v11.0.4
  3. * https://github.com/jackocnr/intl-tel-input.git
  4. * Licensed under the MIT license
  5. */
  6. // wrap in UMD - see https://github.com/umdjs/umd/blob/master/jqueryPluginCommonjs.js
  7. (function(factory) {
  8. if (typeof define === "function" && define.amd) {
  9. define([ "jquery" ], function($) {
  10. factory($, window, document);
  11. });
  12. } else if (typeof module === "object" && module.exports) {
  13. module.exports = factory(require("jquery"), window, document);
  14. } else {
  15. factory(jQuery, window, document);
  16. }
  17. })(function($, window, document, undefined) {
  18. "use strict";
  19. // these vars persist through all instances of the plugin
  20. var pluginName = "intlTelInput", id = 1, // give each instance it's own id for namespaced event handling
  21. defaults = {
  22. // whether or not to allow the dropdown
  23. allowDropdown: true,
  24. // if there is just a dial code in the input: remove it on blur, and re-add it on focus
  25. autoHideDialCode: true,
  26. // add a placeholder in the input with an example number for the selected country
  27. autoPlaceholder: "polite",
  28. // modify the auto placeholder
  29. customPlaceholder: null,
  30. // append menu to a specific element
  31. dropdownContainer: "",
  32. // don't display these countries
  33. excludeCountries: [],
  34. // format the input value during initialisation and on setNumber
  35. formatOnDisplay: true,
  36. // geoIp lookup function
  37. geoIpLookup: null,
  38. // initial country
  39. initialCountry: "",
  40. // don't insert international dial codes
  41. nationalMode: true,
  42. // display only these countries
  43. onlyCountries: [],
  44. // number type to use for placeholders
  45. placeholderNumberType: "MOBILE",
  46. // the countries at the top of the list. defaults to united states and united kingdom
  47. preferredCountries: [ "us", "gb" ],
  48. // display the country dial code next to the selected flag so it's not part of the typed number
  49. separateDialCode: false,
  50. // specify the path to the libphonenumber script to enable validation/formatting
  51. utilsScript: ""
  52. }, keys = {
  53. UP: 38,
  54. DOWN: 40,
  55. ENTER: 13,
  56. ESC: 27,
  57. PLUS: 43,
  58. A: 65,
  59. Z: 90,
  60. SPACE: 32,
  61. TAB: 9
  62. }, // https://en.wikipedia.org/wiki/List_of_North_American_Numbering_Plan_area_codes#Non-geographic_area_codes
  63. regionlessNanpNumbers = [ "800", "822", "833", "844", "855", "866", "877", "880", "881", "882", "883", "884", "885", "886", "887", "888", "889" ];
  64. // keep track of if the window.load event has fired as impossible to check after the fact
  65. $(window).on("load", function() {
  66. // UPDATE: use a public static field so we can fudge it in the tests
  67. $.fn[pluginName].windowLoaded = true;
  68. });
  69. function Plugin(element, options) {
  70. this.telInput = $(element);
  71. this.options = $.extend({}, defaults, options);
  72. // event namespace
  73. this.ns = "." + pluginName + id++;
  74. // Chrome, FF, Safari, IE9+
  75. this.isGoodBrowser = Boolean(element.setSelectionRange);
  76. this.hadInitialPlaceholder = Boolean($(element).attr("placeholder"));
  77. }
  78. Plugin.prototype = {
  79. _init: function() {
  80. // if in nationalMode, disable options relating to dial codes
  81. if (this.options.nationalMode) {
  82. this.options.autoHideDialCode = false;
  83. }
  84. // if separateDialCode then doesn't make sense to A) insert dial code into input (autoHideDialCode), and B) display national numbers (because we're displaying the country dial code next to them)
  85. if (this.options.separateDialCode) {
  86. this.options.autoHideDialCode = this.options.nationalMode = false;
  87. }
  88. // we cannot just test screen size as some smartphones/website meta tags will report desktop resolutions
  89. // Note: for some reason jasmine breaks if you put this in the main Plugin function with the rest of these declarations
  90. // Note: to target Android Mobiles (and not Tablets), we must find "Android" and "Mobile"
  91. this.isMobile = /Android.+Mobile|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
  92. if (this.isMobile) {
  93. // trigger the mobile dropdown css
  94. $("body").addClass("iti-mobile");
  95. // on mobile, we want a full screen dropdown, so we must append it to the body
  96. if (!this.options.dropdownContainer) {
  97. this.options.dropdownContainer = "body";
  98. }
  99. }
  100. // we return these deferred objects from the _init() call so they can be watched, and then we resolve them when each specific request returns
  101. // Note: again, jasmine breaks when I put these in the Plugin function
  102. this.autoCountryDeferred = new $.Deferred();
  103. this.utilsScriptDeferred = new $.Deferred();
  104. // in various situations there could be no country selected initially, but we need to be able to assume this variable exists
  105. this.selectedCountryData = {};
  106. // process all the data: onlyCountries, excludeCountries, preferredCountries etc
  107. this._processCountryData();
  108. // generate the markup
  109. this._generateMarkup();
  110. // set the initial state of the input value and the selected flag
  111. this._setInitialState();
  112. // start all of the event listeners: autoHideDialCode, input keydown, selectedFlag click
  113. this._initListeners();
  114. // utils script, and auto country
  115. this._initRequests();
  116. // return the deferreds
  117. return [ this.autoCountryDeferred, this.utilsScriptDeferred ];
  118. },
  119. /********************
  120. * PRIVATE METHODS
  121. ********************/
  122. // prepare all of the country data, including onlyCountries, excludeCountries and preferredCountries options
  123. _processCountryData: function() {
  124. // process onlyCountries or excludeCountries array if present
  125. this._processAllCountries();
  126. // process the countryCodes map
  127. this._processCountryCodes();
  128. // process the preferredCountries
  129. this._processPreferredCountries();
  130. },
  131. // add a country code to this.countryCodes
  132. _addCountryCode: function(iso2, dialCode, priority) {
  133. if (!(dialCode in this.countryCodes)) {
  134. this.countryCodes[dialCode] = [];
  135. }
  136. var index = priority || 0;
  137. this.countryCodes[dialCode][index] = iso2;
  138. },
  139. // filter the given countries using the process function
  140. _filterCountries: function(countryArray, processFunc) {
  141. var i;
  142. // standardise case
  143. for (i = 0; i < countryArray.length; i++) {
  144. countryArray[i] = countryArray[i].toLowerCase();
  145. }
  146. // build instance country array
  147. this.countries = [];
  148. for (i = 0; i < allCountries.length; i++) {
  149. if (processFunc($.inArray(allCountries[i].iso2, countryArray))) {
  150. this.countries.push(allCountries[i]);
  151. }
  152. }
  153. },
  154. // process onlyCountries or excludeCountries array if present
  155. _processAllCountries: function() {
  156. if (this.options.onlyCountries.length) {
  157. // process onlyCountries option
  158. this._filterCountries(this.options.onlyCountries, function(arrayPos) {
  159. // if country is in array
  160. return arrayPos > -1;
  161. });
  162. } else if (this.options.excludeCountries.length) {
  163. // process excludeCountries option
  164. this._filterCountries(this.options.excludeCountries, function(arrayPos) {
  165. // if country is not in array
  166. return arrayPos == -1;
  167. });
  168. } else {
  169. this.countries = allCountries;
  170. }
  171. },
  172. // process the countryCodes map
  173. _processCountryCodes: function() {
  174. this.countryCodes = {};
  175. for (var i = 0; i < this.countries.length; i++) {
  176. var c = this.countries[i];
  177. this._addCountryCode(c.iso2, c.dialCode, c.priority);
  178. // area codes
  179. if (c.areaCodes) {
  180. for (var j = 0; j < c.areaCodes.length; j++) {
  181. // full dial code is country code + dial code
  182. this._addCountryCode(c.iso2, c.dialCode + c.areaCodes[j]);
  183. }
  184. }
  185. }
  186. },
  187. // process preferred countries - iterate through the preferences, fetching the country data for each one
  188. _processPreferredCountries: function() {
  189. this.preferredCountries = [];
  190. for (var i = 0; i < this.options.preferredCountries.length; i++) {
  191. var countryCode = this.options.preferredCountries[i].toLowerCase(), countryData = this._getCountryData(countryCode, false, true);
  192. if (countryData) {
  193. this.preferredCountries.push(countryData);
  194. }
  195. }
  196. },
  197. // generate all of the markup for the plugin: the selected flag overlay, and the dropdown
  198. _generateMarkup: function() {
  199. // prevent autocomplete as there's no safe, cross-browser event we can react to, so it can easily put the plugin in an inconsistent state e.g. the wrong flag selected for the autocompleted number, which on submit could mean the wrong number is saved (esp in nationalMode)
  200. this.telInput.attr("autocomplete", "off");
  201. // containers (mostly for positioning)
  202. var parentClass = "intl-tel-input";
  203. if (this.options.allowDropdown) {
  204. parentClass += " allow-dropdown";
  205. }
  206. if (this.options.separateDialCode) {
  207. parentClass += " separate-dial-code";
  208. }
  209. this.telInput.wrap($("<div>", {
  210. "class": parentClass
  211. }));
  212. this.flagsContainer = $("<div>", {
  213. "class": "flag-container"
  214. }).insertBefore(this.telInput);
  215. // currently selected flag (displayed to left of input)
  216. var selectedFlag = $("<div>", {
  217. "class": "selected-flag"
  218. });
  219. selectedFlag.appendTo(this.flagsContainer);
  220. this.selectedFlagInner = $("<div>", {
  221. "class": "iti-flag"
  222. }).appendTo(selectedFlag);
  223. if (this.options.separateDialCode) {
  224. this.selectedDialCode = $("<div>", {
  225. "class": "selected-dial-code"
  226. }).appendTo(selectedFlag);
  227. }
  228. if (this.options.allowDropdown) {
  229. // make element focusable and tab naviagable
  230. selectedFlag.attr("tabindex", "0");
  231. // CSS triangle
  232. $("<div>", {
  233. "class": "iti-arrow"
  234. }).appendTo(selectedFlag);
  235. // country dropdown: preferred countries, then divider, then all countries
  236. this.countryList = $("<ul>", {
  237. "class": "country-list hide"
  238. });
  239. if (this.preferredCountries.length) {
  240. this._appendListItems(this.preferredCountries, "preferred");
  241. $("<li>", {
  242. "class": "divider"
  243. }).appendTo(this.countryList);
  244. }
  245. this._appendListItems(this.countries, "");
  246. // this is useful in lots of places
  247. this.countryListItems = this.countryList.children(".country");
  248. // create dropdownContainer markup
  249. if (this.options.dropdownContainer) {
  250. this.dropdown = $("<div>", {
  251. "class": "intl-tel-input iti-container"
  252. }).append(this.countryList);
  253. } else {
  254. this.countryList.appendTo(this.flagsContainer);
  255. }
  256. } else {
  257. // a little hack so we don't break anything
  258. this.countryListItems = $();
  259. }
  260. },
  261. // add a country <li> to the countryList <ul> container
  262. _appendListItems: function(countries, className) {
  263. // we create so many DOM elements, it is faster to build a temp string
  264. // and then add everything to the DOM in one go at the end
  265. var tmp = "";
  266. // for each country
  267. for (var i = 0; i < countries.length; i++) {
  268. var c = countries[i];
  269. // open the list item
  270. tmp += "<li class='country " + className + "' data-dial-code='" + c.dialCode + "' data-country-code='" + c.iso2 + "'>";
  271. // add the flag
  272. tmp += "<div class='flag-box'><div class='iti-flag " + c.iso2 + "'></div></div>";
  273. // and the country name and dial code
  274. tmp += "<span class='country-name'>" + c.name + "</span>";
  275. tmp += "<span class='dial-code'>+" + c.dialCode + "</span>";
  276. // close the list item
  277. tmp += "</li>";
  278. }
  279. this.countryList.append(tmp);
  280. },
  281. // set the initial state of the input value and the selected flag by:
  282. // 1. extracting a dial code from the given number
  283. // 2. using explicit initialCountry
  284. // 3. picking the first preferred country
  285. // 4. picking the first country
  286. _setInitialState: function() {
  287. var val = this.telInput.val();
  288. // if we already have a dial code, and it's not a regionlessNanp we can go ahead and set the flag, else fall back to default
  289. if (this._getDialCode(val) && !this._isRegionlessNanp(val)) {
  290. this._updateFlagFromNumber(val);
  291. } else if (this.options.initialCountry !== "auto") {
  292. // see if we should select a flag
  293. if (this.options.initialCountry) {
  294. this._setFlag(this.options.initialCountry.toLowerCase());
  295. } else {
  296. // no dial code and no initialCountry, so default to first in list
  297. this.defaultCountry = this.preferredCountries.length ? this.preferredCountries[0].iso2 : this.countries[0].iso2;
  298. if (!val) {
  299. this._setFlag(this.defaultCountry);
  300. }
  301. }
  302. // if empty and no nationalMode and no autoHideDialCode then insert the default dial code
  303. if (!val && !this.options.nationalMode && !this.options.autoHideDialCode && !this.options.separateDialCode) {
  304. this.telInput.val("+" + this.selectedCountryData.dialCode);
  305. }
  306. }
  307. // NOTE: if initialCountry is set to auto, that will be handled separately
  308. // format
  309. if (val) {
  310. // this wont be run after _updateDialCode as that's only called if no val
  311. this._updateValFromNumber(val);
  312. }
  313. },
  314. // initialise the main event listeners: input keyup, and click selected flag
  315. _initListeners: function() {
  316. this._initKeyListeners();
  317. if (this.options.autoHideDialCode) {
  318. this._initFocusListeners();
  319. }
  320. if (this.options.allowDropdown) {
  321. this._initDropdownListeners();
  322. }
  323. },
  324. // initialise the dropdown listeners
  325. _initDropdownListeners: function() {
  326. var that = this;
  327. // hack for input nested inside label: clicking the selected-flag to open the dropdown would then automatically trigger a 2nd click on the input which would close it again
  328. var label = this.telInput.closest("label");
  329. if (label.length) {
  330. label.on("click" + this.ns, function(e) {
  331. // if the dropdown is closed, then focus the input, else ignore the click
  332. if (that.countryList.hasClass("hide")) {
  333. that.telInput.focus();
  334. } else {
  335. e.preventDefault();
  336. }
  337. });
  338. }
  339. // toggle country dropdown on click
  340. var selectedFlag = this.selectedFlagInner.parent();
  341. selectedFlag.on("click" + this.ns, function(e) {
  342. // only intercept this event if we're opening the dropdown
  343. // else let it bubble up to the top ("click-off-to-close" listener)
  344. // we cannot just stopPropagation as it may be needed to close another instance
  345. if (that.countryList.hasClass("hide") && !that.telInput.prop("disabled") && !that.telInput.prop("readonly")) {
  346. that._showDropdown();
  347. }
  348. });
  349. // open dropdown list if currently focused
  350. this.flagsContainer.on("keydown" + that.ns, function(e) {
  351. var isDropdownHidden = that.countryList.hasClass("hide");
  352. if (isDropdownHidden && (e.which == keys.UP || e.which == keys.DOWN || e.which == keys.SPACE || e.which == keys.ENTER)) {
  353. // prevent form from being submitted if "ENTER" was pressed
  354. e.preventDefault();
  355. // prevent event from being handled again by document
  356. e.stopPropagation();
  357. that._showDropdown();
  358. }
  359. // allow navigation from dropdown to input on TAB
  360. if (e.which == keys.TAB) {
  361. that._closeDropdown();
  362. }
  363. });
  364. },
  365. // init many requests: utils script / geo ip lookup
  366. _initRequests: function() {
  367. var that = this;
  368. // if the user has specified the path to the utils script, fetch it on window.load, else resolve
  369. if (this.options.utilsScript) {
  370. // if the plugin is being initialised after the window.load event has already been fired
  371. if ($.fn[pluginName].windowLoaded) {
  372. $.fn[pluginName].loadUtils(this.options.utilsScript, this.utilsScriptDeferred);
  373. } else {
  374. // wait until the load event so we don't block any other requests e.g. the flags image
  375. $(window).on("load", function() {
  376. $.fn[pluginName].loadUtils(that.options.utilsScript, that.utilsScriptDeferred);
  377. });
  378. }
  379. } else {
  380. this.utilsScriptDeferred.resolve();
  381. }
  382. if (this.options.initialCountry === "auto") {
  383. this._loadAutoCountry();
  384. } else {
  385. this.autoCountryDeferred.resolve();
  386. }
  387. },
  388. // perform the geo ip lookup
  389. _loadAutoCountry: function() {
  390. var that = this;
  391. // 3 options:
  392. // 1) already loaded (we're done)
  393. // 2) not already started loading (start)
  394. // 3) already started loading (do nothing - just wait for loading callback to fire)
  395. if ($.fn[pluginName].autoCountry) {
  396. this.handleAutoCountry();
  397. } else if (!$.fn[pluginName].startedLoadingAutoCountry) {
  398. // don't do this twice!
  399. $.fn[pluginName].startedLoadingAutoCountry = true;
  400. if (typeof this.options.geoIpLookup === "function") {
  401. this.options.geoIpLookup(function(countryCode) {
  402. $.fn[pluginName].autoCountry = countryCode.toLowerCase();
  403. // tell all instances the auto country is ready
  404. // TODO: this should just be the current instances
  405. // UPDATE: use setTimeout in case their geoIpLookup function calls this callback straight away (e.g. if they have already done the geo ip lookup somewhere else). Using setTimeout means that the current thread of execution will finish before executing this, which allows the plugin to finish initialising.
  406. setTimeout(function() {
  407. $(".intl-tel-input input").intlTelInput("handleAutoCountry");
  408. });
  409. });
  410. }
  411. }
  412. },
  413. // initialize any key listeners
  414. _initKeyListeners: function() {
  415. var that = this;
  416. // update flag on keyup
  417. // (keep this listener separate otherwise the setTimeout breaks all the tests)
  418. this.telInput.on("keyup" + this.ns, function() {
  419. if (that._updateFlagFromNumber(that.telInput.val())) {
  420. that._triggerCountryChange();
  421. }
  422. });
  423. // update flag on cut/paste events (now supported in all major browsers)
  424. this.telInput.on("cut" + this.ns + " paste" + this.ns, function() {
  425. // hack because "paste" event is fired before input is updated
  426. setTimeout(function() {
  427. if (that._updateFlagFromNumber(that.telInput.val())) {
  428. that._triggerCountryChange();
  429. }
  430. });
  431. });
  432. },
  433. // adhere to the input's maxlength attr
  434. _cap: function(number) {
  435. var max = this.telInput.attr("maxlength");
  436. return max && number.length > max ? number.substr(0, max) : number;
  437. },
  438. // listen for mousedown, focus and blur
  439. _initFocusListeners: function() {
  440. var that = this;
  441. // mousedown decides where the cursor goes, so if we're focusing we must preventDefault as we'll be inserting the dial code, and we want the cursor to be at the end no matter where they click
  442. this.telInput.on("mousedown" + this.ns, function(e) {
  443. if (!that.telInput.is(":focus") && !that.telInput.val()) {
  444. e.preventDefault();
  445. // but this also cancels the focus, so we must trigger that manually
  446. that.telInput.focus();
  447. }
  448. });
  449. // on focus: if empty, insert the dial code for the currently selected flag
  450. this.telInput.on("focus" + this.ns, function(e) {
  451. if (!that.telInput.val() && !that.telInput.prop("readonly") && that.selectedCountryData.dialCode) {
  452. // insert the dial code
  453. that.telInput.val("+" + that.selectedCountryData.dialCode);
  454. // after auto-inserting a dial code, if the first key they hit is '+' then assume they are entering a new number, so remove the dial code. use keypress instead of keydown because keydown gets triggered for the shift key (required to hit the + key), and instead of keyup because that shows the new '+' before removing the old one
  455. that.telInput.one("keypress.plus" + that.ns, function(e) {
  456. if (e.which == keys.PLUS) {
  457. that.telInput.val("");
  458. }
  459. });
  460. // after tabbing in, make sure the cursor is at the end we must use setTimeout to get outside of the focus handler as it seems the selection happens after that
  461. setTimeout(function() {
  462. var input = that.telInput[0];
  463. if (that.isGoodBrowser) {
  464. var len = that.telInput.val().length;
  465. input.setSelectionRange(len, len);
  466. }
  467. });
  468. }
  469. });
  470. // on blur or form submit: if just a dial code then remove it
  471. var form = this.telInput.prop("form");
  472. if (form) {
  473. $(form).on("submit" + this.ns, function() {
  474. that._removeEmptyDialCode();
  475. });
  476. }
  477. this.telInput.on("blur" + this.ns, function() {
  478. that._removeEmptyDialCode();
  479. });
  480. },
  481. _removeEmptyDialCode: function() {
  482. var value = this.telInput.val(), startsPlus = value.charAt(0) == "+";
  483. if (startsPlus) {
  484. var numeric = this._getNumeric(value);
  485. // if just a plus, or if just a dial code
  486. if (!numeric || this.selectedCountryData.dialCode == numeric) {
  487. this.telInput.val("");
  488. }
  489. }
  490. // remove the keypress listener we added on focus
  491. this.telInput.off("keypress.plus" + this.ns);
  492. },
  493. // extract the numeric digits from the given string
  494. _getNumeric: function(s) {
  495. return s.replace(/\D/g, "");
  496. },
  497. // show the dropdown
  498. _showDropdown: function() {
  499. this._setDropdownPosition();
  500. // update highlighting and scroll to active list item
  501. var activeListItem = this.countryList.children(".active");
  502. if (activeListItem.length) {
  503. this._highlightListItem(activeListItem);
  504. this._scrollTo(activeListItem);
  505. }
  506. // bind all the dropdown-related listeners: mouseover, click, click-off, keydown
  507. this._bindDropdownListeners();
  508. // update the arrow
  509. this.selectedFlagInner.children(".iti-arrow").addClass("up");
  510. },
  511. // decide where to position dropdown (depends on position within viewport, and scroll)
  512. _setDropdownPosition: function() {
  513. var that = this;
  514. if (this.options.dropdownContainer) {
  515. this.dropdown.appendTo(this.options.dropdownContainer);
  516. }
  517. // show the menu and grab the dropdown height
  518. this.dropdownHeight = this.countryList.removeClass("hide").outerHeight();
  519. if (!this.isMobile) {
  520. var pos = this.telInput.offset(), inputTop = pos.top, windowTop = $(window).scrollTop(), // dropdownFitsBelow = (dropdownBottom < windowBottom)
  521. dropdownFitsBelow = inputTop + this.telInput.outerHeight() + this.dropdownHeight < windowTop + $(window).height(), dropdownFitsAbove = inputTop - this.dropdownHeight > windowTop;
  522. // by default, the dropdown will be below the input. If we want to position it above the input, we add the dropup class.
  523. this.countryList.toggleClass("dropup", !dropdownFitsBelow && dropdownFitsAbove);
  524. // if dropdownContainer is enabled, calculate postion
  525. if (this.options.dropdownContainer) {
  526. // by default the dropdown will be directly over the input because it's not in the flow. If we want to position it below, we need to add some extra top value.
  527. var extraTop = !dropdownFitsBelow && dropdownFitsAbove ? 0 : this.telInput.innerHeight();
  528. // calculate placement
  529. this.dropdown.css({
  530. top: inputTop + extraTop,
  531. left: pos.left
  532. });
  533. // close menu on window scroll
  534. $(window).on("scroll" + this.ns, function() {
  535. that._closeDropdown();
  536. });
  537. }
  538. }
  539. },
  540. // we only bind dropdown listeners when the dropdown is open
  541. _bindDropdownListeners: function() {
  542. var that = this;
  543. // when mouse over a list item, just highlight that one
  544. // we add the class "highlight", so if they hit "enter" we know which one to select
  545. this.countryList.on("mouseover" + this.ns, ".country", function(e) {
  546. that._highlightListItem($(this));
  547. });
  548. // listen for country selection
  549. this.countryList.on("click" + this.ns, ".country", function(e) {
  550. that._selectListItem($(this));
  551. });
  552. // click off to close
  553. // (except when this initial opening click is bubbling up)
  554. // we cannot just stopPropagation as it may be needed to close another instance
  555. var isOpening = true;
  556. $("html").on("click" + this.ns, function(e) {
  557. if (!isOpening) {
  558. that._closeDropdown();
  559. }
  560. isOpening = false;
  561. });
  562. // listen for up/down scrolling, enter to select, or letters to jump to country name.
  563. // use keydown as keypress doesn't fire for non-char keys and we want to catch if they
  564. // just hit down and hold it to scroll down (no keyup event).
  565. // listen on the document because that's where key events are triggered if no input has focus
  566. var query = "", queryTimer = null;
  567. $(document).on("keydown" + this.ns, function(e) {
  568. // prevent down key from scrolling the whole page,
  569. // and enter key from submitting a form etc
  570. e.preventDefault();
  571. if (e.which == keys.UP || e.which == keys.DOWN) {
  572. // up and down to navigate
  573. that._handleUpDownKey(e.which);
  574. } else if (e.which == keys.ENTER) {
  575. // enter to select
  576. that._handleEnterKey();
  577. } else if (e.which == keys.ESC) {
  578. // esc to close
  579. that._closeDropdown();
  580. } else if (e.which >= keys.A && e.which <= keys.Z || e.which == keys.SPACE) {
  581. // upper case letters (note: keyup/keydown only return upper case letters)
  582. // jump to countries that start with the query string
  583. if (queryTimer) {
  584. clearTimeout(queryTimer);
  585. }
  586. query += String.fromCharCode(e.which);
  587. that._searchForCountry(query);
  588. // if the timer hits 1 second, reset the query
  589. queryTimer = setTimeout(function() {
  590. query = "";
  591. }, 1e3);
  592. }
  593. });
  594. },
  595. // highlight the next/prev item in the list (and ensure it is visible)
  596. _handleUpDownKey: function(key) {
  597. var current = this.countryList.children(".highlight").first();
  598. var next = key == keys.UP ? current.prev() : current.next();
  599. if (next.length) {
  600. // skip the divider
  601. if (next.hasClass("divider")) {
  602. next = key == keys.UP ? next.prev() : next.next();
  603. }
  604. this._highlightListItem(next);
  605. this._scrollTo(next);
  606. }
  607. },
  608. // select the currently highlighted item
  609. _handleEnterKey: function() {
  610. var currentCountry = this.countryList.children(".highlight").first();
  611. if (currentCountry.length) {
  612. this._selectListItem(currentCountry);
  613. }
  614. },
  615. // find the first list item whose name starts with the query string
  616. _searchForCountry: function(query) {
  617. for (var i = 0; i < this.countries.length; i++) {
  618. if (this._startsWith(this.countries[i].name, query)) {
  619. var listItem = this.countryList.children("[data-country-code=" + this.countries[i].iso2 + "]").not(".preferred");
  620. // update highlighting and scroll
  621. this._highlightListItem(listItem);
  622. this._scrollTo(listItem, true);
  623. break;
  624. }
  625. }
  626. },
  627. // check if (uppercase) string a starts with string b
  628. _startsWith: function(a, b) {
  629. return a.substr(0, b.length).toUpperCase() == b;
  630. },
  631. // update the input's value to the given val (format first if possible)
  632. // NOTE: this is called from _setInitialState, handleUtils and setNumber
  633. _updateValFromNumber: function(number) {
  634. if (this.options.formatOnDisplay && window.intlTelInputUtils && this.selectedCountryData) {
  635. var format = !this.options.separateDialCode && (this.options.nationalMode || number.charAt(0) != "+") ? intlTelInputUtils.numberFormat.NATIONAL : intlTelInputUtils.numberFormat.INTERNATIONAL;
  636. number = intlTelInputUtils.formatNumber(number, this.selectedCountryData.iso2, format);
  637. }
  638. number = this._beforeSetNumber(number);
  639. this.telInput.val(number);
  640. },
  641. // check if need to select a new flag based on the given number
  642. // Note: called from _setInitialState, keyup handler, setNumber
  643. _updateFlagFromNumber: function(number) {
  644. // if we're in nationalMode and we already have US/Canada selected, make sure the number starts with a +1 so _getDialCode will be able to extract the area code
  645. // update: if we dont yet have selectedCountryData, but we're here (trying to update the flag from the number), that means we're initialising the plugin with a number that already has a dial code, so fine to ignore this bit
  646. if (number && this.options.nationalMode && this.selectedCountryData.dialCode == "1" && number.charAt(0) != "+") {
  647. if (number.charAt(0) != "1") {
  648. number = "1" + number;
  649. }
  650. number = "+" + number;
  651. }
  652. // try and extract valid dial code from input
  653. var dialCode = this._getDialCode(number), countryCode = null, numeric = this._getNumeric(number);
  654. if (dialCode) {
  655. // check if one of the matching countries is already selected
  656. var countryCodes = this.countryCodes[this._getNumeric(dialCode)], alreadySelected = $.inArray(this.selectedCountryData.iso2, countryCodes) > -1, // check if the given number contains a NANP area code i.e. the only dialCode that could be extracted was +1 (instead of say +1204) and the actual number's length is >=4
  657. isNanpAreaCode = dialCode == "+1" && numeric.length >= 4, nanpSelected = this.selectedCountryData.dialCode == "1";
  658. // only update the flag if:
  659. // A) NOT (we currently have a NANP flag selected, and the number is a regionlessNanp)
  660. // AND
  661. // B) either a matching country is not already selected OR the number contains a NANP area code (ensure the flag is set to the first matching country)
  662. if (!(nanpSelected && this._isRegionlessNanp(numeric)) && (!alreadySelected || isNanpAreaCode)) {
  663. // if using onlyCountries option, countryCodes[0] may be empty, so we must find the first non-empty index
  664. for (var j = 0; j < countryCodes.length; j++) {
  665. if (countryCodes[j]) {
  666. countryCode = countryCodes[j];
  667. break;
  668. }
  669. }
  670. }
  671. } else if (number.charAt(0) == "+" && numeric.length) {
  672. // invalid dial code, so empty
  673. // Note: use getNumeric here because the number has not been formatted yet, so could contain bad chars
  674. countryCode = "";
  675. } else if (!number || number == "+") {
  676. // empty, or just a plus, so default
  677. countryCode = this.defaultCountry;
  678. }
  679. if (countryCode !== null) {
  680. return this._setFlag(countryCode);
  681. }
  682. return false;
  683. },
  684. // check if the given number is a regionless NANP number (expects the number to contain an international dial code)
  685. _isRegionlessNanp: function(number) {
  686. var numeric = this._getNumeric(number);
  687. if (numeric.charAt(0) == "1") {
  688. var areaCode = numeric.substr(1, 3);
  689. return $.inArray(areaCode, regionlessNanpNumbers) > -1;
  690. }
  691. return false;
  692. },
  693. // remove highlighting from other list items and highlight the given item
  694. _highlightListItem: function(listItem) {
  695. this.countryListItems.removeClass("highlight");
  696. listItem.addClass("highlight");
  697. },
  698. // find the country data for the given country code
  699. // the ignoreOnlyCountriesOption is only used during init() while parsing the onlyCountries array
  700. _getCountryData: function(countryCode, ignoreOnlyCountriesOption, allowFail) {
  701. var countryList = ignoreOnlyCountriesOption ? allCountries : this.countries;
  702. for (var i = 0; i < countryList.length; i++) {
  703. if (countryList[i].iso2 == countryCode) {
  704. return countryList[i];
  705. }
  706. }
  707. if (allowFail) {
  708. return null;
  709. } else {
  710. throw new Error("No country data for '" + countryCode + "'");
  711. }
  712. },
  713. // select the given flag, update the placeholder and the active list item
  714. // Note: called from _setInitialState, _updateFlagFromNumber, _selectListItem, setCountry
  715. _setFlag: function(countryCode) {
  716. var prevCountry = this.selectedCountryData.iso2 ? this.selectedCountryData : {};
  717. // do this first as it will throw an error and stop if countryCode is invalid
  718. this.selectedCountryData = countryCode ? this._getCountryData(countryCode, false, false) : {};
  719. // update the defaultCountry - we only need the iso2 from now on, so just store that
  720. if (this.selectedCountryData.iso2) {
  721. this.defaultCountry = this.selectedCountryData.iso2;
  722. }
  723. this.selectedFlagInner.attr("class", "iti-flag " + countryCode);
  724. // update the selected country's title attribute
  725. var title = countryCode ? this.selectedCountryData.name + ": +" + this.selectedCountryData.dialCode : "Unknown";
  726. this.selectedFlagInner.parent().attr("title", title);
  727. if (this.options.separateDialCode) {
  728. var dialCode = this.selectedCountryData.dialCode ? "+" + this.selectedCountryData.dialCode : "", parent = this.telInput.parent();
  729. if (prevCountry.dialCode) {
  730. parent.removeClass("iti-sdc-" + (prevCountry.dialCode.length + 1));
  731. }
  732. if (dialCode) {
  733. parent.addClass("iti-sdc-" + dialCode.length);
  734. }
  735. this.selectedDialCode.text(dialCode);
  736. }
  737. // and the input's placeholder
  738. this._updatePlaceholder();
  739. // update the active list item
  740. this.countryListItems.removeClass("active");
  741. if (countryCode) {
  742. this.countryListItems.find(".iti-flag." + countryCode).first().closest(".country").addClass("active");
  743. }
  744. // return if the flag has changed or not
  745. return prevCountry.iso2 !== countryCode;
  746. },
  747. // update the input placeholder to an example number from the currently selected country
  748. _updatePlaceholder: function() {
  749. var shouldSetPlaceholder = this.options.autoPlaceholder === "aggressive" || !this.hadInitialPlaceholder && (this.options.autoPlaceholder === true || this.options.autoPlaceholder === "polite");
  750. if (window.intlTelInputUtils && shouldSetPlaceholder) {
  751. var numberType = intlTelInputUtils.numberType[this.options.placeholderNumberType], placeholder = this.selectedCountryData.iso2 ? intlTelInputUtils.getExampleNumber(this.selectedCountryData.iso2, this.options.nationalMode, numberType) : "";
  752. placeholder = this._beforeSetNumber(placeholder);
  753. if (typeof this.options.customPlaceholder === "function") {
  754. placeholder = this.options.customPlaceholder(placeholder, this.selectedCountryData);
  755. }
  756. this.telInput.attr("placeholder", placeholder);
  757. }
  758. },
  759. // called when the user selects a list item from the dropdown
  760. _selectListItem: function(listItem) {
  761. // update selected flag and active list item
  762. var flagChanged = this._setFlag(listItem.attr("data-country-code"));
  763. this._closeDropdown();
  764. this._updateDialCode(listItem.attr("data-dial-code"), true);
  765. // focus the input
  766. this.telInput.focus();
  767. // put cursor at end - this fix is required for FF and IE11 (with nationalMode=false i.e. auto inserting dial code), who try to put the cursor at the beginning the first time
  768. if (this.isGoodBrowser) {
  769. var len = this.telInput.val().length;
  770. this.telInput[0].setSelectionRange(len, len);
  771. }
  772. if (flagChanged) {
  773. this._triggerCountryChange();
  774. }
  775. },
  776. // close the dropdown and unbind any listeners
  777. _closeDropdown: function() {
  778. this.countryList.addClass("hide");
  779. // update the arrow
  780. this.selectedFlagInner.children(".iti-arrow").removeClass("up");
  781. // unbind key events
  782. $(document).off(this.ns);
  783. // unbind click-off-to-close
  784. $("html").off(this.ns);
  785. // unbind hover and click listeners
  786. this.countryList.off(this.ns);
  787. // remove menu from container
  788. if (this.options.dropdownContainer) {
  789. if (!this.isMobile) {
  790. $(window).off("scroll" + this.ns);
  791. }
  792. this.dropdown.detach();
  793. }
  794. },
  795. // check if an element is visible within it's container, else scroll until it is
  796. _scrollTo: function(element, middle) {
  797. var container = this.countryList, containerHeight = container.height(), containerTop = container.offset().top, containerBottom = containerTop + containerHeight, elementHeight = element.outerHeight(), elementTop = element.offset().top, elementBottom = elementTop + elementHeight, newScrollTop = elementTop - containerTop + container.scrollTop(), middleOffset = containerHeight / 2 - elementHeight / 2;
  798. if (elementTop < containerTop) {
  799. // scroll up
  800. if (middle) {
  801. newScrollTop -= middleOffset;
  802. }
  803. container.scrollTop(newScrollTop);
  804. } else if (elementBottom > containerBottom) {
  805. // scroll down
  806. if (middle) {
  807. newScrollTop += middleOffset;
  808. }
  809. var heightDifference = containerHeight - elementHeight;
  810. container.scrollTop(newScrollTop - heightDifference);
  811. }
  812. },
  813. // replace any existing dial code with the new one
  814. // Note: called from _selectListItem and setCountry
  815. _updateDialCode: function(newDialCode, hasSelectedListItem) {
  816. var inputVal = this.telInput.val(), newNumber;
  817. // save having to pass this every time
  818. newDialCode = "+" + newDialCode;
  819. if (inputVal.charAt(0) == "+") {
  820. // there's a plus so we're dealing with a replacement (doesn't matter if nationalMode or not)
  821. var prevDialCode = this._getDialCode(inputVal);
  822. if (prevDialCode) {
  823. // current number contains a valid dial code, so replace it
  824. newNumber = inputVal.replace(prevDialCode, newDialCode);
  825. } else {
  826. // current number contains an invalid dial code, so ditch it
  827. // (no way to determine where the invalid dial code ends and the rest of the number begins)
  828. newNumber = newDialCode;
  829. }
  830. } else if (this.options.nationalMode || this.options.separateDialCode) {
  831. // don't do anything
  832. return;
  833. } else {
  834. // nationalMode is disabled
  835. if (inputVal) {
  836. // there is an existing value with no dial code: prefix the new dial code
  837. newNumber = newDialCode + inputVal;
  838. } else if (hasSelectedListItem || !this.options.autoHideDialCode) {
  839. // no existing value and either they've just selected a list item, or autoHideDialCode is disabled: insert new dial code
  840. newNumber = newDialCode;
  841. } else {
  842. return;
  843. }
  844. }
  845. this.telInput.val(newNumber);
  846. },
  847. // try and extract a valid international dial code from a full telephone number
  848. // Note: returns the raw string inc plus character and any whitespace/dots etc
  849. _getDialCode: function(number) {
  850. var dialCode = "";
  851. // only interested in international numbers (starting with a plus)
  852. if (number.charAt(0) == "+") {
  853. var numericChars = "";
  854. // iterate over chars
  855. for (var i = 0; i < number.length; i++) {
  856. var c = number.charAt(i);
  857. // if char is number
  858. if ($.isNumeric(c)) {
  859. numericChars += c;
  860. // if current numericChars make a valid dial code
  861. if (this.countryCodes[numericChars]) {
  862. // store the actual raw string (useful for matching later)
  863. dialCode = number.substr(0, i + 1);
  864. }
  865. // longest dial code is 4 chars
  866. if (numericChars.length == 4) {
  867. break;
  868. }
  869. }
  870. }
  871. }
  872. return dialCode;
  873. },
  874. // get the input val, adding the dial code if separateDialCode is enabled
  875. _getFullNumber: function() {
  876. var val = $.trim(this.telInput.val()), dialCode = this.selectedCountryData.dialCode, prefix, numericVal = this._getNumeric(val), // normalized means ensure starts with a 1, so we can match against the full dial code
  877. normalizedVal = numericVal.charAt(0) == "1" ? numericVal : "1" + numericVal;
  878. if (this.options.separateDialCode) {
  879. prefix = "+" + dialCode;
  880. } else if (val.charAt(0) != "+" && val.charAt(0) != "1" && dialCode && dialCode.charAt(0) == "1" && dialCode.length == 4 && dialCode != normalizedVal.substr(0, 4)) {
  881. // if the user has entered a national NANP number, then ensure it includes the full dial code / area code
  882. prefix = dialCode.substr(1);
  883. } else {
  884. prefix = "";
  885. }
  886. return prefix + val;
  887. },
  888. // remove the dial code if separateDialCode is enabled
  889. _beforeSetNumber: function(number) {
  890. if (this.options.separateDialCode) {
  891. var dialCode = this._getDialCode(number);
  892. if (dialCode) {
  893. // US dialCode is "+1", which is what we want
  894. // CA dialCode is "+1 123", which is wrong - should be "+1" (as it has multiple area codes)
  895. // AS dialCode is "+1 684", which is what we want
  896. // Solution: if the country has area codes, then revert to just the dial code
  897. if (this.selectedCountryData.areaCodes !== null) {
  898. dialCode = "+" + this.selectedCountryData.dialCode;
  899. }
  900. // a lot of numbers will have a space separating the dial code and the main number, and some NANP numbers will have a hyphen e.g. +1 684-733-1234 - in both cases we want to get rid of it
  901. // NOTE: don't just trim all non-numerics as may want to preserve an open parenthesis etc
  902. var start = number[dialCode.length] === " " || number[dialCode.length] === "-" ? dialCode.length + 1 : dialCode.length;
  903. number = number.substr(start);
  904. }
  905. }
  906. return this._cap(number);
  907. },
  908. // trigger the 'countrychange' event
  909. _triggerCountryChange: function() {
  910. this.telInput.trigger("countrychange", this.selectedCountryData);
  911. },
  912. /**************************
  913. * SECRET PUBLIC METHODS
  914. **************************/
  915. // this is called when the geoip call returns
  916. handleAutoCountry: function() {
  917. if (this.options.initialCountry === "auto") {
  918. // we must set this even if there is an initial val in the input: in case the initial val is invalid and they delete it - they should see their auto country
  919. this.defaultCountry = $.fn[pluginName].autoCountry;
  920. // if there's no initial value in the input, then update the flag
  921. if (!this.telInput.val()) {
  922. this.setCountry(this.defaultCountry);
  923. }
  924. this.autoCountryDeferred.resolve();
  925. }
  926. },
  927. // this is called when the utils request completes
  928. handleUtils: function() {
  929. // if the request was successful
  930. if (window.intlTelInputUtils) {
  931. // if there's an initial value in the input, then format it
  932. if (this.telInput.val()) {
  933. this._updateValFromNumber(this.telInput.val());
  934. }
  935. this._updatePlaceholder();
  936. }
  937. this.utilsScriptDeferred.resolve();
  938. },
  939. /********************
  940. * PUBLIC METHODS
  941. ********************/
  942. // remove plugin
  943. destroy: function() {
  944. if (this.allowDropdown) {
  945. // make sure the dropdown is closed (and unbind listeners)
  946. this._closeDropdown();
  947. // click event to open dropdown
  948. this.selectedFlagInner.parent().off(this.ns);
  949. // label click hack
  950. this.telInput.closest("label").off(this.ns);
  951. }
  952. // unbind submit event handler on form
  953. if (this.options.autoHideDialCode) {
  954. var form = this.telInput.prop("form");
  955. if (form) {
  956. $(form).off(this.ns);
  957. }
  958. }
  959. // unbind all events: key events, and focus/blur events if autoHideDialCode=true
  960. this.telInput.off(this.ns);
  961. // remove markup (but leave the original input)
  962. var container = this.telInput.parent();
  963. container.before(this.telInput).remove();
  964. },
  965. // get the extension from the current number
  966. getExtension: function() {
  967. if (window.intlTelInputUtils) {
  968. return intlTelInputUtils.getExtension(this._getFullNumber(), this.selectedCountryData.iso2);
  969. }
  970. return "";
  971. },
  972. // format the number to the given format
  973. getNumber: function(format) {
  974. if (window.intlTelInputUtils) {
  975. return intlTelInputUtils.formatNumber(this._getFullNumber(), this.selectedCountryData.iso2, format);
  976. }
  977. return "";
  978. },
  979. // get the type of the entered number e.g. landline/mobile
  980. getNumberType: function() {
  981. if (window.intlTelInputUtils) {
  982. return intlTelInputUtils.getNumberType(this._getFullNumber(), this.selectedCountryData.iso2);
  983. }
  984. return -99;
  985. },
  986. // get the country data for the currently selected flag
  987. getSelectedCountryData: function() {
  988. return this.selectedCountryData;
  989. },
  990. // get the validation error
  991. getValidationError: function() {
  992. if (window.intlTelInputUtils) {
  993. return intlTelInputUtils.getValidationError(this._getFullNumber(), this.selectedCountryData.iso2);
  994. }
  995. return -99;
  996. },
  997. // validate the input val - assumes the global function isValidNumber (from utilsScript)
  998. isValidNumber: function() {
  999. var val = $.trim(this._getFullNumber()), countryCode = this.options.nationalMode ? this.selectedCountryData.iso2 : "";
  1000. return window.intlTelInputUtils ? intlTelInputUtils.isValidNumber(val, countryCode) : null;
  1001. },
  1002. // update the selected flag, and update the input val accordingly
  1003. setCountry: function(countryCode) {
  1004. countryCode = countryCode.toLowerCase();
  1005. // check if already selected
  1006. if (!this.selectedFlagInner.hasClass(countryCode)) {
  1007. this._setFlag(countryCode);
  1008. this._updateDialCode(this.selectedCountryData.dialCode, false);
  1009. this._triggerCountryChange();
  1010. }
  1011. },
  1012. // set the input value and update the flag
  1013. setNumber: function(number) {
  1014. // we must update the flag first, which updates this.selectedCountryData, which is used for formatting the number before displaying it
  1015. var flagChanged = this._updateFlagFromNumber(number);
  1016. this._updateValFromNumber(number);
  1017. if (flagChanged) {
  1018. this._triggerCountryChange();
  1019. }
  1020. }
  1021. };
  1022. // using https://github.com/jquery-boilerplate/jquery-boilerplate/wiki/Extending-jQuery-Boilerplate
  1023. // (adapted to allow public functions)
  1024. $.fn[pluginName] = function(options) {
  1025. var args = arguments;
  1026. // Is the first parameter an object (options), or was omitted,
  1027. // instantiate a new instance of the plugin.
  1028. if (options === undefined || typeof options === "object") {
  1029. // collect all of the deferred objects for all instances created with this selector
  1030. var deferreds = [];
  1031. this.each(function() {
  1032. if (!$.data(this, "plugin_" + pluginName)) {
  1033. var instance = new Plugin(this, options);
  1034. var instanceDeferreds = instance._init();
  1035. // we now have 2 deffereds: 1 for auto country, 1 for utils script
  1036. deferreds.push(instanceDeferreds[0]);
  1037. deferreds.push(instanceDeferreds[1]);
  1038. $.data(this, "plugin_" + pluginName, instance);
  1039. }
  1040. });
  1041. // return the promise from the "master" deferred object that tracks all the others
  1042. return $.when.apply(null, deferreds);
  1043. } else if (typeof options === "string" && options[0] !== "_") {
  1044. // If the first parameter is a string and it doesn't start
  1045. // with an underscore or "contains" the `init`-function,
  1046. // treat this as a call to a public method.
  1047. // Cache the method call to make it possible to return a value
  1048. var returns;
  1049. this.each(function() {
  1050. var instance = $.data(this, "plugin_" + pluginName);
  1051. // Tests that there's already a plugin-instance
  1052. // and checks that the requested public method exists
  1053. if (instance instanceof Plugin && typeof instance[options] === "function") {
  1054. // Call the method of our plugin instance,
  1055. // and pass it the supplied arguments.
  1056. returns = instance[options].apply(instance, Array.prototype.slice.call(args, 1));
  1057. }
  1058. // Allow instances to be destroyed via the 'destroy' method
  1059. if (options === "destroy") {
  1060. $.data(this, "plugin_" + pluginName, null);
  1061. }
  1062. });
  1063. // If the earlier cached method gives a value back return the value,
  1064. // otherwise return this to preserve chainability.
  1065. return returns !== undefined ? returns : this;
  1066. }
  1067. };
  1068. /********************
  1069. * STATIC METHODS
  1070. ********************/
  1071. // get the country data object
  1072. $.fn[pluginName].getCountryData = function() {
  1073. return allCountries;
  1074. };
  1075. // load the utils script
  1076. $.fn[pluginName].loadUtils = function(path, utilsScriptDeferred) {
  1077. if (!$.fn[pluginName].loadedUtilsScript) {
  1078. // don't do this twice! (dont just check if window.intlTelInputUtils exists as if init plugin multiple times in quick succession, it may not have finished loading yet)
  1079. $.fn[pluginName].loadedUtilsScript = true;
  1080. // dont use $.getScript as it prevents caching
  1081. $.ajax({
  1082. type: "GET",
  1083. url: path,
  1084. complete: function() {
  1085. // tell all instances that the utils request is complete
  1086. $(".intl-tel-input input").intlTelInput("handleUtils");
  1087. },
  1088. dataType: "script",
  1089. cache: true
  1090. });
  1091. } else if (utilsScriptDeferred) {
  1092. utilsScriptDeferred.resolve();
  1093. }
  1094. };
  1095. // default options
  1096. $.fn[pluginName].defaults = defaults;
  1097. // version
  1098. $.fn[pluginName].version = "11.0.4";
  1099. // Array of country objects for the flag dropdown.
  1100. // Here is the criteria for the plugin to support a given country/territory
  1101. // - It has an iso2 code: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
  1102. // - It has a country calling code: https://en.wikipedia.org/wiki/List_of_country_calling_codes
  1103. // - It has a flag in the region-flags project: https://github.com/behdad/region-flags/tree/gh-pages/png
  1104. // - It is supported by libphonenumber (it must be listed here): https://github.com/googlei18n/libphonenumber/blob/master/resources/ShortNumberMetadata.xml
  1105. // Each country array has the following information:
  1106. // [
  1107. // Country name,
  1108. // iso2 code,
  1109. // International dial code,
  1110. // Order (if >1 country with same dial code),
  1111. // Area codes
  1112. // ]
  1113. var allCountries = [ [ "Afghanistan (‫افغانستان‬‎)", "af", "93" ], [ "Albania (Shqipëri)", "al", "355" ], [ "Algeria (‫الجزائر‬‎)", "dz", "213" ], [ "American Samoa", "as", "1684" ], [ "Andorra", "ad", "376" ], [ "Angola", "ao", "244" ], [ "Anguilla", "ai", "1264" ], [ "Antigua and Barbuda", "ag", "1268" ], [ "Argentina", "ar", "54" ], [ "Armenia (Հայաստան)", "am", "374" ], [ "Aruba", "aw", "297" ], [ "Australia", "au", "61", 0 ], [ "Austria (Österreich)", "at", "43" ], [ "Azerbaijan (Azərbaycan)", "az", "994" ], [ "Bahamas", "bs", "1242" ], [ "Bahrain (‫البحرين‬‎)", "bh", "973" ], [ "Bangladesh (বাংলাদেশ)", "bd", "880" ], [ "Barbados", "bb", "1246" ], [ "Belarus (Беларусь)", "by", "375" ], [ "Belgium (België)", "be", "32" ], [ "Belize", "bz", "501" ], [ "Benin (Bénin)", "bj", "229" ], [ "Bermuda", "bm", "1441" ], [ "Bhutan (འབྲུག)", "bt", "975" ], [ "Bolivia", "bo", "591" ], [ "Bosnia and Herzegovina (Босна и Херцеговина)", "ba", "387" ], [ "Botswana", "bw", "267" ], [ "Brazil (Brasil)", "br", "55" ], [ "British Indian Ocean Territory", "io", "246" ], [ "British Virgin Islands", "vg", "1284" ], [ "Brunei", "bn", "673" ], [ "Bulgaria (България)", "bg", "359" ], [ "Burkina Faso", "bf", "226" ], [ "Burundi (Uburundi)", "bi", "257" ], [ "Cambodia (កម្ពុជា)", "kh", "855" ], [ "Cameroon (Cameroun)", "cm", "237" ], [ "Canada", "ca", "1", 1, [ "204", "226", "236", "249", "250", "289", "306", "343", "365", "387", "403", "416", "418", "431", "437", "438", "450", "506", "514", "519", "548", "579", "581", "587", "604", "613", "639", "647", "672", "705", "709", "742", "778", "780", "782", "807", "819", "825", "867", "873", "902", "905" ] ], [ "Cape Verde (Kabu Verdi)", "cv", "238" ], [ "Caribbean Netherlands", "bq", "599", 1 ], [ "Cayman Islands", "ky", "1345" ], [ "Central African Republic (République centrafricaine)", "cf", "236" ], [ "Chad (Tchad)", "td", "235" ], [ "Chile", "cl", "56" ], [ "China (中国)", "cn", "86" ], [ "Christmas Island", "cx", "61", 2 ], [ "Cocos (Keeling) Islands", "cc", "61", 1 ], [ "Colombia", "co", "57" ], [ "Comoros (‫جزر القمر‬‎)", "km", "269" ], [ "Congo (DRC) (Jamhuri ya Kidemokrasia ya Kongo)", "cd", "243" ], [ "Congo (Republic) (Congo-Brazzaville)", "cg", "242" ], [ "Cook Islands", "ck", "682" ], [ "Costa Rica", "cr", "506" ], [ "Côte d’Ivoire", "ci", "225" ], [ "Croatia (Hrvatska)", "hr", "385" ], [ "Cuba", "cu", "53" ], [ "Curaçao", "cw", "599", 0 ], [ "Cyprus (Κύπρος)", "cy", "357" ], [ "Czech Republic (Česká republika)", "cz", "420" ], [ "Denmark (Danmark)", "dk", "45" ], [ "Djibouti", "dj", "253" ], [ "Dominica", "dm", "1767" ], [ "Dominican Republic (República Dominicana)", "do", "1", 2, [ "809", "829", "849" ] ], [ "Ecuador", "ec", "593" ], [ "Egypt (‫مصر‬‎)", "eg", "20" ], [ "El Salvador", "sv", "503" ], [ "Equatorial Guinea (Guinea Ecuatorial)", "gq", "240" ], [ "Eritrea", "er", "291" ], [ "Estonia (Eesti)", "ee", "372" ], [ "Ethiopia", "et", "251" ], [ "Falkland Islands (Islas Malvinas)", "fk", "500" ], [ "Faroe Islands (Føroyar)", "fo", "298" ], [ "Fiji", "fj", "679" ], [ "Finland (Suomi)", "fi", "358", 0 ], [ "France", "fr", "33" ], [ "French Guiana (Guyane française)", "gf", "594" ], [ "French Polynesia (Polynésie française)", "pf", "689" ], [ "Gabon", "ga", "241" ], [ "Gambia", "gm", "220" ], [ "Georgia (საქართველო)", "ge", "995" ], [ "Germany (Deutschland)", "de", "49" ], [ "Ghana (Gaana)", "gh", "233" ], [ "Gibraltar", "gi", "350" ], [ "Greece (Ελλάδα)", "gr", "30" ], [ "Greenland (Kalaallit Nunaat)", "gl", "299" ], [ "Grenada", "gd", "1473" ], [ "Guadeloupe", "gp", "590", 0 ], [ "Guam", "gu", "1671" ], [ "Guatemala", "gt", "502" ], [ "Guernsey", "gg", "44", 1 ], [ "Guinea (Guinée)", "gn", "224" ], [ "Guinea-Bissau (Guiné Bissau)", "gw", "245" ], [ "Guyana", "gy", "592" ], [ "Haiti", "ht", "509" ], [ "Honduras", "hn", "504" ], [ "Hong Kong (香港)", "hk", "852" ], [ "Hungary (Magyarország)", "hu", "36" ], [ "Iceland (Ísland)", "is", "354" ], [ "India (भारत)", "in", "91" ], [ "Indonesia", "id", "62" ], [ "Iran (‫ایران‬‎)", "ir", "98" ], [ "Iraq (‫العراق‬‎)", "iq", "964" ], [ "Ireland", "ie", "353" ], [ "Isle of Man", "im", "44", 2 ], [ "Israel (‫ישראל‬‎)", "il", "972" ], [ "Italy (Italia)", "it", "39", 0 ], [ "Jamaica", "jm", "1876" ], [ "Japan (日本)", "jp", "81" ], [ "Jersey", "je", "44", 3 ], [ "Jordan (‫الأردن‬‎)", "jo", "962" ], [ "Kazakhstan (Казахстан)", "kz", "7", 1 ], [ "Kenya", "ke", "254" ], [ "Kiribati", "ki", "686" ], [ "Kosovo", "xk", "383" ], [ "Kuwait (‫الكويت‬‎)", "kw", "965" ], [ "Kyrgyzstan (Кыргызстан)", "kg", "996" ], [ "Laos (ລາວ)", "la", "856" ], [ "Latvia (Latvija)", "lv", "371" ], [ "Lebanon (‫لبنان‬‎)", "lb", "961" ], [ "Lesotho", "ls", "266" ], [ "Liberia", "lr", "231" ], [ "Libya (‫ليبيا‬‎)", "ly", "218" ], [ "Liechtenstein", "li", "423" ], [ "Lithuania (Lietuva)", "lt", "370" ], [ "Luxembourg", "lu", "352" ], [ "Macau (澳門)", "mo", "853" ], [ "Macedonia (FYROM) (Македонија)", "mk", "389" ], [ "Madagascar (Madagasikara)", "mg", "261" ], [ "Malawi", "mw", "265" ], [ "Malaysia", "my", "60" ], [ "Maldives", "mv", "960" ], [ "Mali", "ml", "223" ], [ "Malta", "mt", "356" ], [ "Marshall Islands", "mh", "692" ], [ "Martinique", "mq", "596" ], [ "Mauritania (‫موريتانيا‬‎)", "mr", "222" ], [ "Mauritius (Moris)", "mu", "230" ], [ "Mayotte", "yt", "262", 1 ], [ "Mexico (México)", "mx", "52" ], [ "Micronesia", "fm", "691" ], [ "Moldova (Republica Moldova)", "md", "373" ], [ "Monaco", "mc", "377" ], [ "Mongolia (Монгол)", "mn", "976" ], [ "Montenegro (Crna Gora)", "me", "382" ], [ "Montserrat", "ms", "1664" ], [ "Morocco (‫المغرب‬‎)", "ma", "212", 0 ], [ "Mozambique (Moçambique)", "mz", "258" ], [ "Myanmar (Burma) (မြန်မာ)", "mm", "95" ], [ "Namibia (Namibië)", "na", "264" ], [ "Nauru", "nr", "674" ], [ "Nepal (नेपाल)", "np", "977" ], [ "Netherlands (Nederland)", "nl", "31" ], [ "New Caledonia (Nouvelle-Calédonie)", "nc", "687" ], [ "New Zealand", "nz", "64" ], [ "Nicaragua", "ni", "505" ], [ "Niger (Nijar)", "ne", "227" ], [ "Nigeria", "ng", "234" ], [ "Niue", "nu", "683" ], [ "Norfolk Island", "nf", "672" ], [ "North Korea (조선 민주주의 인민 공화국)", "kp", "850" ], [ "Northern Mariana Islands", "mp", "1670" ], [ "Norway (Norge)", "no", "47", 0 ], [ "Oman (‫عُمان‬‎)", "om", "968" ], [ "Pakistan (‫پاکستان‬‎)", "pk", "92" ], [ "Palau", "pw", "680" ], [ "Palestine (‫فلسطين‬‎)", "ps", "970" ], [ "Panama (Panamá)", "pa", "507" ], [ "Papua New Guinea", "pg", "675" ], [ "Paraguay", "py", "595" ], [ "Peru (Perú)", "pe", "51" ], [ "Philippines", "ph", "63" ], [ "Poland (Polska)", "pl", "48" ], [ "Portugal", "pt", "351" ], [ "Puerto Rico", "pr", "1", 3, [ "787", "939" ] ], [ "Qatar (‫قطر‬‎)", "qa", "974" ], [ "Réunion (La Réunion)", "re", "262", 0 ], [ "Romania (România)", "ro", "40" ], [ "Russia (Россия)", "ru", "7", 0 ], [ "Rwanda", "rw", "250" ], [ "Saint Barthélemy (Saint-Barthélemy)", "bl", "590", 1 ], [ "Saint Helena", "sh", "290" ], [ "Saint Kitts and Nevis", "kn", "1869" ], [ "Saint Lucia", "lc", "1758" ], [ "Saint Martin (Saint-Martin (partie française))", "mf", "590", 2 ], [ "Saint Pierre and Miquelon (Saint-Pierre-et-Miquelon)", "pm", "508" ], [ "Saint Vincent and the Grenadines", "vc", "1784" ], [ "Samoa", "ws", "685" ], [ "San Marino", "sm", "378" ], [ "São Tomé and Príncipe (São Tomé e Príncipe)", "st", "239" ], [ "Saudi Arabia (‫المملكة العربية السعودية‬‎)", "sa", "966" ], [ "Senegal (Sénégal)", "sn", "221" ], [ "Serbia (Србија)", "rs", "381" ], [ "Seychelles", "sc", "248" ], [ "Sierra Leone", "sl", "232" ], [ "Singapore", "sg", "65" ], [ "Sint Maarten", "sx", "1721" ], [ "Slovakia (Slovensko)", "sk", "421" ], [ "Slovenia (Slovenija)", "si", "386" ], [ "Solomon Islands", "sb", "677" ], [ "Somalia (Soomaaliya)", "so", "252" ], [ "South Africa", "za", "27" ], [ "South Korea (대한민국)", "kr", "82" ], [ "South Sudan (‫جنوب السودان‬‎)", "ss", "211" ], [ "Spain (España)", "es", "34" ], [ "Sri Lanka (ශ්‍රී ලංකාව)", "lk", "94" ], [ "Sudan (‫السودان‬‎)", "sd", "249" ], [ "Suriname", "sr", "597" ], [ "Svalbard and Jan Mayen", "sj", "47", 1 ], [ "Swaziland", "sz", "268" ], [ "Sweden (Sverige)", "se", "46" ], [ "Switzerland (Schweiz)", "ch", "41" ], [ "Syria (‫سوريا‬‎)", "sy", "963" ], [ "Taiwan (台灣)", "tw", "886" ], [ "Tajikistan", "tj", "992" ], [ "Tanzania", "tz", "255" ], [ "Thailand (ไทย)", "th", "66" ], [ "Timor-Leste", "tl", "670" ], [ "Togo", "tg", "228" ], [ "Tokelau", "tk", "690" ], [ "Tonga", "to", "676" ], [ "Trinidad and Tobago", "tt", "1868" ], [ "Tunisia (‫تونس‬‎)", "tn", "216" ], [ "Turkey (Türkiye)", "tr", "90" ], [ "Turkmenistan", "tm", "993" ], [ "Turks and Caicos Islands", "tc", "1649" ], [ "Tuvalu", "tv", "688" ], [ "U.S. Virgin Islands", "vi", "1340" ], [ "Uganda", "ug", "256" ], [ "Ukraine (Україна)", "ua", "380" ], [ "United Arab Emirates (‫الإمارات العربية المتحدة‬‎)", "ae", "971" ], [ "United Kingdom", "gb", "44", 0 ], [ "United States", "us", "1", 0 ], [ "Uruguay", "uy", "598" ], [ "Uzbekistan (Oʻzbekiston)", "uz", "998" ], [ "Vanuatu", "vu", "678" ], [ "Vatican City (Città del Vaticano)", "va", "39", 1 ], [ "Venezuela", "ve", "58" ], [ "Vietnam (Việt Nam)", "vn", "84" ], [ "Wallis and Futuna", "wf", "681" ], [ "Western Sahara (‫الصحراء الغربية‬‎)", "eh", "212", 1 ], [ "Yemen (‫اليمن‬‎)", "ye", "967" ], [ "Zambia", "zm", "260" ], [ "Zimbabwe", "zw", "263" ], [ "Åland Islands", "ax", "358", 1 ] ];
  1114. // loop over all of the countries above
  1115. for (var i = 0; i < allCountries.length; i++) {
  1116. var c = allCountries[i];
  1117. allCountries[i] = {
  1118. name: c[0],
  1119. iso2: c[1],
  1120. dialCode: c[2],
  1121. priority: c[3] || 0,
  1122. areaCodes: c[4] || null
  1123. };
  1124. }
  1125. });