intlTelInput.js 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  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. this.telInput.wrap($("<div>", {
  203. }));
  204. this.flagsContainer = $("<div>", {
  205. "class": "flag-container"
  206. }).insertBefore(this.telInput);
  207. // currently selected flag (displayed to left of input)
  208. var selectedFlag = $("<div>", {
  209. "class": "selected-flag"
  210. });
  211. selectedFlag.appendTo(this.flagsContainer);
  212. this.selectedFlagInner = $("<div>", {
  213. "class": "iti-flag"
  214. }).appendTo(selectedFlag);
  215. if (this.options.separateDialCode) {
  216. this.selectedDialCode = $("<div>", {
  217. "class": "selected-dial-code"
  218. }).appendTo(selectedFlag);
  219. }
  220. if (this.options.allowDropdown) {
  221. // make element focusable and tab naviagable
  222. selectedFlag.attr("tabindex", "0");
  223. // CSS triangle
  224. $("<div>", {
  225. "class": "iti-arrow"
  226. }).appendTo(selectedFlag);
  227. // country dropdown: preferred countries, then divider, then all countries
  228. this.countryList = $("<ul>", {
  229. "class": "country-list hide"
  230. });
  231. if (this.preferredCountries.length) {
  232. this._appendListItems(this.preferredCountries, "preferred");
  233. $("<li>", {
  234. "class": "divider"
  235. }).appendTo(this.countryList);
  236. }
  237. this._appendListItems(this.countries, "");
  238. // this is useful in lots of places
  239. this.countryListItems = this.countryList.children(".country");
  240. // create dropdownContainer markup
  241. if (this.options.dropdownContainer) {
  242. this.dropdown = $("<div>", {
  243. "class": "intl-tel-input iti-container"
  244. }).append(this.countryList);
  245. } else {
  246. this.countryList.appendTo(this.flagsContainer);
  247. }
  248. } else {
  249. // a little hack so we don't break anything
  250. this.countryListItems = $();
  251. }
  252. },
  253. // add a country <li> to the countryList <ul> container
  254. _appendListItems: function(countries, className) {
  255. // we create so many DOM elements, it is faster to build a temp string
  256. // and then add everything to the DOM in one go at the end
  257. var tmp = "";
  258. // for each country
  259. for (var i = 0; i < countries.length; i++) {
  260. var c = countries[i];
  261. // open the list item
  262. tmp += "<li class='country " + className + "' data-dial-code='" + c.dialCode + "' data-country-code='" + c.iso2 + "'>";
  263. // add the flag
  264. tmp += "<div class='flag-box'><div class='iti-flag " + c.iso2 + "'></div></div>";
  265. // and the country name and dial code
  266. tmp += "<span class='country-name'>" + c.name + "</span>";
  267. tmp += "<span class='dial-code'>+" + c.dialCode + "</span>";
  268. // close the list item
  269. tmp += "</li>";
  270. }
  271. this.countryList.append(tmp);
  272. },
  273. // set the initial state of the input value and the selected flag by:
  274. // 1. extracting a dial code from the given number
  275. // 2. using explicit initialCountry
  276. // 3. picking the first preferred country
  277. // 4. picking the first country
  278. _setInitialState: function() {
  279. var val = this.telInput.val();
  280. // 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
  281. if (this._getDialCode(val) && !this._isRegionlessNanp(val)) {
  282. this._updateFlagFromNumber(val);
  283. } else if (this.options.initialCountry !== "auto") {
  284. // see if we should select a flag
  285. if (this.options.initialCountry) {
  286. this._setFlag(this.options.initialCountry.toLowerCase());
  287. } else {
  288. // no dial code and no initialCountry, so default to first in list
  289. this.defaultCountry = this.preferredCountries.length ? this.preferredCountries[0].iso2 : this.countries[0].iso2;
  290. if (!val) {
  291. this._setFlag(this.defaultCountry);
  292. }
  293. }
  294. // if empty and no nationalMode and no autoHideDialCode then insert the default dial code
  295. if (!val && !this.options.nationalMode && !this.options.autoHideDialCode && !this.options.separateDialCode) {
  296. this.telInput.val("+" + this.selectedCountryData.dialCode);
  297. }
  298. }
  299. // NOTE: if initialCountry is set to auto, that will be handled separately
  300. // format
  301. if (val) {
  302. // this wont be run after _updateDialCode as that's only called if no val
  303. this._updateValFromNumber(val);
  304. }
  305. },
  306. // initialise the main event listeners: input keyup, and click selected flag
  307. _initListeners: function() {
  308. this._initKeyListeners();
  309. if (this.options.autoHideDialCode) {
  310. this._initFocusListeners();
  311. }
  312. if (this.options.allowDropdown) {
  313. this._initDropdownListeners();
  314. }
  315. },
  316. // initialise the dropdown listeners
  317. _initDropdownListeners: function() {
  318. var that = this;
  319. // 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
  320. var label = this.telInput.closest("label");
  321. if (label.length) {
  322. label.on("click" + this.ns, function(e) {
  323. // if the dropdown is closed, then focus the input, else ignore the click
  324. if (that.countryList.hasClass("hide")) {
  325. that.telInput.focus();
  326. } else {
  327. e.preventDefault();
  328. }
  329. });
  330. }
  331. // toggle country dropdown on click
  332. var selectedFlag = this.selectedFlagInner.parent();
  333. selectedFlag.on("click" + this.ns, function(e) {
  334. // only intercept this event if we're opening the dropdown
  335. // else let it bubble up to the top ("click-off-to-close" listener)
  336. // we cannot just stopPropagation as it may be needed to close another instance
  337. if (that.countryList.hasClass("hide") && !that.telInput.prop("disabled") && !that.telInput.prop("readonly")) {
  338. that._showDropdown();
  339. }
  340. });
  341. // open dropdown list if currently focused
  342. this.flagsContainer.on("keydown" + that.ns, function(e) {
  343. var isDropdownHidden = that.countryList.hasClass("hide");
  344. if (isDropdownHidden && (e.which == keys.UP || e.which == keys.DOWN || e.which == keys.SPACE || e.which == keys.ENTER)) {
  345. // prevent form from being submitted if "ENTER" was pressed
  346. e.preventDefault();
  347. // prevent event from being handled again by document
  348. e.stopPropagation();
  349. that._showDropdown();
  350. }
  351. // allow navigation from dropdown to input on TAB
  352. if (e.which == keys.TAB) {
  353. that._closeDropdown();
  354. }
  355. });
  356. },
  357. // init many requests: utils script / geo ip lookup
  358. _initRequests: function() {
  359. var that = this;
  360. // if the user has specified the path to the utils script, fetch it on window.load, else resolve
  361. if (this.options.utilsScript) {
  362. // if the plugin is being initialised after the window.load event has already been fired
  363. if ($.fn[pluginName].windowLoaded) {
  364. $.fn[pluginName].loadUtils(this.options.utilsScript, this.utilsScriptDeferred);
  365. } else {
  366. // wait until the load event so we don't block any other requests e.g. the flags image
  367. $(window).on("load", function() {
  368. $.fn[pluginName].loadUtils(that.options.utilsScript, that.utilsScriptDeferred);
  369. });
  370. }
  371. } else {
  372. this.utilsScriptDeferred.resolve();
  373. }
  374. if (this.options.initialCountry === "auto") {
  375. this._loadAutoCountry();
  376. } else {
  377. this.autoCountryDeferred.resolve();
  378. }
  379. },
  380. // perform the geo ip lookup
  381. _loadAutoCountry: function() {
  382. var that = this;
  383. // 3 options:
  384. // 1) already loaded (we're done)
  385. // 2) not already started loading (start)
  386. // 3) already started loading (do nothing - just wait for loading callback to fire)
  387. if ($.fn[pluginName].autoCountry) {
  388. this.handleAutoCountry();
  389. } else if (!$.fn[pluginName].startedLoadingAutoCountry) {
  390. // don't do this twice!
  391. $.fn[pluginName].startedLoadingAutoCountry = true;
  392. if (typeof this.options.geoIpLookup === "function") {
  393. this.options.geoIpLookup(function(countryCode) {
  394. $.fn[pluginName].autoCountry = countryCode.toLowerCase();
  395. // tell all instances the auto country is ready
  396. // TODO: this should just be the current instances
  397. // 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.
  398. setTimeout(function() {
  399. $(".intl-tel-input input").intlTelInput("handleAutoCountry");
  400. });
  401. });
  402. }
  403. }
  404. },
  405. // initialize any key listeners
  406. _initKeyListeners: function() {
  407. var that = this;
  408. // update flag on keyup
  409. // (keep this listener separate otherwise the setTimeout breaks all the tests)
  410. this.telInput.on("keyup" + this.ns, function() {
  411. if (that._updateFlagFromNumber(that.telInput.val())) {
  412. that._triggerCountryChange();
  413. }
  414. });
  415. // update flag on cut/paste events (now supported in all major browsers)
  416. this.telInput.on("cut" + this.ns + " paste" + this.ns, function() {
  417. // hack because "paste" event is fired before input is updated
  418. setTimeout(function() {
  419. if (that._updateFlagFromNumber(that.telInput.val())) {
  420. that._triggerCountryChange();
  421. }
  422. });
  423. });
  424. },
  425. // adhere to the input's maxlength attr
  426. _cap: function(number) {
  427. var max = this.telInput.attr("maxlength");
  428. return max && number.length > max ? number.substr(0, max) : number;
  429. },
  430. // listen for mousedown, focus and blur
  431. _initFocusListeners: function() {
  432. var that = this;
  433. // 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
  434. this.telInput.on("mousedown" + this.ns, function(e) {
  435. if (!that.telInput.is(":focus") && !that.telInput.val()) {
  436. e.preventDefault();
  437. // but this also cancels the focus, so we must trigger that manually
  438. that.telInput.focus();
  439. }
  440. });
  441. // on focus: if empty, insert the dial code for the currently selected flag
  442. this.telInput.on("focus" + this.ns, function(e) {
  443. if (!that.telInput.val() && !that.telInput.prop("readonly") && that.selectedCountryData.dialCode) {
  444. // insert the dial code
  445. that.telInput.val("+" + that.selectedCountryData.dialCode);
  446. // 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
  447. that.telInput.one("keypress.plus" + that.ns, function(e) {
  448. if (e.which == keys.PLUS) {
  449. that.telInput.val("");
  450. }
  451. });
  452. // 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
  453. setTimeout(function() {
  454. var input = that.telInput[0];
  455. if (that.isGoodBrowser) {
  456. var len = that.telInput.val().length;
  457. input.setSelectionRange(len, len);
  458. }
  459. });
  460. }
  461. });
  462. // on blur or form submit: if just a dial code then remove it
  463. var form = this.telInput.prop("form");
  464. if (form) {
  465. $(form).on("submit" + this.ns, function() {
  466. that._removeEmptyDialCode();
  467. });
  468. }
  469. this.telInput.on("blur" + this.ns, function() {
  470. that._removeEmptyDialCode();
  471. });
  472. },
  473. _removeEmptyDialCode: function() {
  474. var value = this.telInput.val(), startsPlus = value.charAt(0) == "+";
  475. if (startsPlus) {
  476. var numeric = this._getNumeric(value);
  477. // if just a plus, or if just a dial code
  478. if (!numeric || this.selectedCountryData.dialCode == numeric) {
  479. this.telInput.val("");
  480. }
  481. }
  482. // remove the keypress listener we added on focus
  483. this.telInput.off("keypress.plus" + this.ns);
  484. },
  485. // extract the numeric digits from the given string
  486. _getNumeric: function(s) {
  487. return s.replace(/\D/g, "");
  488. },
  489. // show the dropdown
  490. _showDropdown: function() {
  491. this._setDropdownPosition();
  492. // update highlighting and scroll to active list item
  493. var activeListItem = this.countryList.children(".active");
  494. if (activeListItem.length) {
  495. this._highlightListItem(activeListItem);
  496. this._scrollTo(activeListItem);
  497. }
  498. // bind all the dropdown-related listeners: mouseover, click, click-off, keydown
  499. this._bindDropdownListeners();
  500. // update the arrow
  501. this.selectedFlagInner.children(".iti-arrow").addClass("up");
  502. },
  503. // decide where to position dropdown (depends on position within viewport, and scroll)
  504. _setDropdownPosition: function() {
  505. var that = this;
  506. if (this.options.dropdownContainer) {
  507. this.dropdown.appendTo(this.options.dropdownContainer);
  508. }
  509. // show the menu and grab the dropdown height
  510. this.dropdownHeight = this.countryList.removeClass("hide").outerHeight();
  511. if (!this.isMobile) {
  512. var pos = this.telInput.offset(), inputTop = pos.top, windowTop = $(window).scrollTop(), // dropdownFitsBelow = (dropdownBottom < windowBottom)
  513. dropdownFitsBelow = inputTop + this.telInput.outerHeight() + this.dropdownHeight < windowTop + $(window).height(), dropdownFitsAbove = inputTop - this.dropdownHeight > windowTop;
  514. // by default, the dropdown will be below the input. If we want to position it above the input, we add the dropup class.
  515. this.countryList.toggleClass("dropup", !dropdownFitsBelow && dropdownFitsAbove);
  516. // if dropdownContainer is enabled, calculate postion
  517. if (this.options.dropdownContainer) {
  518. // 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.
  519. var extraTop = !dropdownFitsBelow && dropdownFitsAbove ? 0 : this.telInput.innerHeight();
  520. // calculate placement
  521. this.dropdown.css({
  522. top: inputTop + extraTop,
  523. left: pos.left
  524. });
  525. // close menu on window scroll
  526. $(window).on("scroll" + this.ns, function() {
  527. that._closeDropdown();
  528. });
  529. }
  530. }
  531. },
  532. // we only bind dropdown listeners when the dropdown is open
  533. _bindDropdownListeners: function() {
  534. var that = this;
  535. // when mouse over a list item, just highlight that one
  536. // we add the class "highlight", so if they hit "enter" we know which one to select
  537. this.countryList.on("mouseover" + this.ns, ".country", function(e) {
  538. that._highlightListItem($(this));
  539. });
  540. // listen for country selection
  541. this.countryList.on("click" + this.ns, ".country", function(e) {
  542. that._selectListItem($(this));
  543. });
  544. // click off to close
  545. // (except when this initial opening click is bubbling up)
  546. // we cannot just stopPropagation as it may be needed to close another instance
  547. var isOpening = true;
  548. $("html").on("click" + this.ns, function(e) {
  549. if (!isOpening) {
  550. that._closeDropdown();
  551. }
  552. isOpening = false;
  553. });
  554. // listen for up/down scrolling, enter to select, or letters to jump to country name.
  555. // use keydown as keypress doesn't fire for non-char keys and we want to catch if they
  556. // just hit down and hold it to scroll down (no keyup event).
  557. // listen on the document because that's where key events are triggered if no input has focus
  558. var query = "", queryTimer = null;
  559. $(document).on("keydown" + this.ns, function(e) {
  560. // prevent down key from scrolling the whole page,
  561. // and enter key from submitting a form etc
  562. e.preventDefault();
  563. if (e.which == keys.UP || e.which == keys.DOWN) {
  564. // up and down to navigate
  565. that._handleUpDownKey(e.which);
  566. } else if (e.which == keys.ENTER) {
  567. // enter to select
  568. that._handleEnterKey();
  569. } else if (e.which == keys.ESC) {
  570. // esc to close
  571. that._closeDropdown();
  572. } else if (e.which >= keys.A && e.which <= keys.Z || e.which == keys.SPACE) {
  573. // upper case letters (note: keyup/keydown only return upper case letters)
  574. // jump to countries that start with the query string
  575. if (queryTimer) {
  576. clearTimeout(queryTimer);
  577. }
  578. query += String.fromCharCode(e.which);
  579. that._searchForCountry(query);
  580. // if the timer hits 1 second, reset the query
  581. queryTimer = setTimeout(function() {
  582. query = "";
  583. }, 1e3);
  584. }
  585. });
  586. },
  587. // highlight the next/prev item in the list (and ensure it is visible)
  588. _handleUpDownKey: function(key) {
  589. var current = this.countryList.children(".highlight").first();
  590. var next = key == keys.UP ? current.prev() : current.next();
  591. if (next.length) {
  592. // skip the divider
  593. if (next.hasClass("divider")) {
  594. next = key == keys.UP ? next.prev() : next.next();
  595. }
  596. this._highlightListItem(next);
  597. this._scrollTo(next);
  598. }
  599. },
  600. // select the currently highlighted item
  601. _handleEnterKey: function() {
  602. var currentCountry = this.countryList.children(".highlight").first();
  603. if (currentCountry.length) {
  604. this._selectListItem(currentCountry);
  605. }
  606. },
  607. // find the first list item whose name starts with the query string
  608. _searchForCountry: function(query) {
  609. for (var i = 0; i < this.countries.length; i++) {
  610. if (this._startsWith(this.countries[i].name, query)) {
  611. var listItem = this.countryList.children("[data-country-code=" + this.countries[i].iso2 + "]").not(".preferred");
  612. // update highlighting and scroll
  613. this._highlightListItem(listItem);
  614. this._scrollTo(listItem, true);
  615. break;
  616. }
  617. }
  618. },
  619. // check if (uppercase) string a starts with string b
  620. _startsWith: function(a, b) {
  621. return a.substr(0, b.length).toUpperCase() == b;
  622. },
  623. // update the input's value to the given val (format first if possible)
  624. // NOTE: this is called from _setInitialState, handleUtils and setNumber
  625. _updateValFromNumber: function(number) {
  626. if (this.options.formatOnDisplay && window.intlTelInputUtils && this.selectedCountryData) {
  627. var format = !this.options.separateDialCode && (this.options.nationalMode || number.charAt(0) != "+") ? intlTelInputUtils.numberFormat.NATIONAL : intlTelInputUtils.numberFormat.INTERNATIONAL;
  628. number = intlTelInputUtils.formatNumber(number, this.selectedCountryData.iso2, format);
  629. }
  630. number = this._beforeSetNumber(number);
  631. this.telInput.val(number);
  632. },
  633. // check if need to select a new flag based on the given number
  634. // Note: called from _setInitialState, keyup handler, setNumber
  635. _updateFlagFromNumber: function(number) {
  636. // 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
  637. // 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
  638. if (number && this.options.nationalMode && this.selectedCountryData.dialCode == "1" && number.charAt(0) != "+") {
  639. if (number.charAt(0) != "1") {
  640. number = "1" + number;
  641. }
  642. number = "+" + number;
  643. }
  644. // try and extract valid dial code from input
  645. var dialCode = this._getDialCode(number), countryCode = null, numeric = this._getNumeric(number);
  646. if (dialCode) {
  647. // check if one of the matching countries is already selected
  648. 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
  649. isNanpAreaCode = dialCode == "+1" && numeric.length >= 4, nanpSelected = this.selectedCountryData.dialCode == "1";
  650. // only update the flag if:
  651. // A) NOT (we currently have a NANP flag selected, and the number is a regionlessNanp)
  652. // AND
  653. // 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)
  654. if (!(nanpSelected && this._isRegionlessNanp(numeric)) && (!alreadySelected || isNanpAreaCode)) {
  655. // if using onlyCountries option, countryCodes[0] may be empty, so we must find the first non-empty index
  656. for (var j = 0; j < countryCodes.length; j++) {
  657. if (countryCodes[j]) {
  658. countryCode = countryCodes[j];
  659. break;
  660. }
  661. }
  662. }
  663. } else if (number.charAt(0) == "+" && numeric.length) {
  664. // invalid dial code, so empty
  665. // Note: use getNumeric here because the number has not been formatted yet, so could contain bad chars
  666. countryCode = "";
  667. } else if (!number || number == "+") {
  668. // empty, or just a plus, so default
  669. countryCode = this.defaultCountry;
  670. }
  671. if (countryCode !== null) {
  672. return this._setFlag(countryCode);
  673. }
  674. return false;
  675. },
  676. // check if the given number is a regionless NANP number (expects the number to contain an international dial code)
  677. _isRegionlessNanp: function(number) {
  678. var numeric = this._getNumeric(number);
  679. if (numeric.charAt(0) == "1") {
  680. var areaCode = numeric.substr(1, 3);
  681. return $.inArray(areaCode, regionlessNanpNumbers) > -1;
  682. }
  683. return false;
  684. },
  685. // remove highlighting from other list items and highlight the given item
  686. _highlightListItem: function(listItem) {
  687. this.countryListItems.removeClass("highlight");
  688. listItem.addClass("highlight");
  689. },
  690. // find the country data for the given country code
  691. // the ignoreOnlyCountriesOption is only used during init() while parsing the onlyCountries array
  692. _getCountryData: function(countryCode, ignoreOnlyCountriesOption, allowFail) {
  693. var countryList = ignoreOnlyCountriesOption ? allCountries : this.countries;
  694. for (var i = 0; i < countryList.length; i++) {
  695. if (countryList[i].iso2 == countryCode) {
  696. return countryList[i];
  697. }
  698. }
  699. if (allowFail) {
  700. return null;
  701. } else {
  702. throw new Error("No country data for '" + countryCode + "'");
  703. }
  704. },
  705. // select the given flag, update the placeholder and the active list item
  706. // Note: called from _setInitialState, _updateFlagFromNumber, _selectListItem, setCountry
  707. _setFlag: function(countryCode) {
  708. var prevCountry = this.selectedCountryData.iso2 ? this.selectedCountryData : {};
  709. // do this first as it will throw an error and stop if countryCode is invalid
  710. this.selectedCountryData = countryCode ? this._getCountryData(countryCode, false, false) : {};
  711. // update the defaultCountry - we only need the iso2 from now on, so just store that
  712. if (this.selectedCountryData.iso2) {
  713. this.defaultCountry = this.selectedCountryData.iso2;
  714. }
  715. this.selectedFlagInner.attr("class", "iti-flag " + countryCode);
  716. // update the selected country's title attribute
  717. var title = countryCode ? this.selectedCountryData.name + ": +" + this.selectedCountryData.dialCode : "Unknown";
  718. this.selectedFlagInner.parent().attr("title", title);
  719. if (this.options.separateDialCode) {
  720. var dialCode = this.selectedCountryData.dialCode ? "+" + this.selectedCountryData.dialCode : "", parent = this.telInput.parent();
  721. this.selectedDialCode.text(dialCode);
  722. }
  723. // and the input's placeholder
  724. this._updatePlaceholder();
  725. // update the active list item
  726. this.countryListItems.removeClass("active");
  727. if (countryCode) {
  728. this.countryListItems.find(".iti-flag." + countryCode).first().closest(".country").addClass("active");
  729. }
  730. // return if the flag has changed or not
  731. return prevCountry.iso2 !== countryCode;
  732. },
  733. // update the input placeholder to an example number from the currently selected country
  734. _updatePlaceholder: function() {
  735. var shouldSetPlaceholder = this.options.autoPlaceholder === "aggressive" || !this.hadInitialPlaceholder && (this.options.autoPlaceholder === true || this.options.autoPlaceholder === "polite");
  736. if (window.intlTelInputUtils && shouldSetPlaceholder) {
  737. var numberType = intlTelInputUtils.numberType[this.options.placeholderNumberType], placeholder = this.selectedCountryData.iso2 ? intlTelInputUtils.getExampleNumber(this.selectedCountryData.iso2, this.options.nationalMode, numberType) : "";
  738. placeholder = this._beforeSetNumber(placeholder);
  739. if (typeof this.options.customPlaceholder === "function") {
  740. placeholder = this.options.customPlaceholder(placeholder, this.selectedCountryData);
  741. }
  742. this.telInput.attr("placeholder", placeholder);
  743. }
  744. },
  745. // called when the user selects a list item from the dropdown
  746. _selectListItem: function(listItem) {
  747. // update selected flag and active list item
  748. var flagChanged = this._setFlag(listItem.attr("data-country-code"));
  749. this._closeDropdown();
  750. this._updateDialCode(listItem.attr("data-dial-code"), true);
  751. // focus the input
  752. this.telInput.focus();
  753. // 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
  754. if (this.isGoodBrowser) {
  755. var len = this.telInput.val().length;
  756. this.telInput[0].setSelectionRange(len, len);
  757. }
  758. if (flagChanged) {
  759. this._triggerCountryChange();
  760. }
  761. },
  762. // close the dropdown and unbind any listeners
  763. _closeDropdown: function() {
  764. this.countryList.addClass("hide");
  765. // update the arrow
  766. this.selectedFlagInner.children(".iti-arrow").removeClass("up");
  767. // unbind key events
  768. $(document).off(this.ns);
  769. // unbind click-off-to-close
  770. $("html").off(this.ns);
  771. // unbind hover and click listeners
  772. this.countryList.off(this.ns);
  773. // remove menu from container
  774. if (this.options.dropdownContainer) {
  775. if (!this.isMobile) {
  776. $(window).off("scroll" + this.ns);
  777. }
  778. this.dropdown.detach();
  779. }
  780. },
  781. // check if an element is visible within it's container, else scroll until it is
  782. _scrollTo: function(element, middle) {
  783. 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;
  784. if (elementTop < containerTop) {
  785. // scroll up
  786. if (middle) {
  787. newScrollTop -= middleOffset;
  788. }
  789. container.scrollTop(newScrollTop);
  790. } else if (elementBottom > containerBottom) {
  791. // scroll down
  792. if (middle) {
  793. newScrollTop += middleOffset;
  794. }
  795. var heightDifference = containerHeight - elementHeight;
  796. container.scrollTop(newScrollTop - heightDifference);
  797. }
  798. },
  799. // replace any existing dial code with the new one
  800. // Note: called from _selectListItem and setCountry
  801. _updateDialCode: function(newDialCode, hasSelectedListItem) {
  802. var inputVal = this.telInput.val(), newNumber;
  803. // save having to pass this every time
  804. newDialCode = "+" + newDialCode;
  805. if (inputVal.charAt(0) == "+") {
  806. // there's a plus so we're dealing with a replacement (doesn't matter if nationalMode or not)
  807. var prevDialCode = this._getDialCode(inputVal);
  808. if (prevDialCode) {
  809. // current number contains a valid dial code, so replace it
  810. newNumber = inputVal.replace(prevDialCode, newDialCode);
  811. } else {
  812. // current number contains an invalid dial code, so ditch it
  813. // (no way to determine where the invalid dial code ends and the rest of the number begins)
  814. newNumber = newDialCode;
  815. }
  816. } else if (this.options.nationalMode || this.options.separateDialCode) {
  817. // don't do anything
  818. return;
  819. } else {
  820. // nationalMode is disabled
  821. if (inputVal) {
  822. // there is an existing value with no dial code: prefix the new dial code
  823. newNumber = newDialCode + inputVal;
  824. } else if (hasSelectedListItem || !this.options.autoHideDialCode) {
  825. // no existing value and either they've just selected a list item, or autoHideDialCode is disabled: insert new dial code
  826. newNumber = newDialCode;
  827. } else {
  828. return;
  829. }
  830. }
  831. this.telInput.val(newNumber);
  832. },
  833. // try and extract a valid international dial code from a full telephone number
  834. // Note: returns the raw string inc plus character and any whitespace/dots etc
  835. _getDialCode: function(number) {
  836. var dialCode = "";
  837. // only interested in international numbers (starting with a plus)
  838. if (number.charAt(0) == "+") {
  839. var numericChars = "";
  840. // iterate over chars
  841. for (var i = 0; i < number.length; i++) {
  842. var c = number.charAt(i);
  843. // if char is number
  844. if ($.isNumeric(c)) {
  845. numericChars += c;
  846. // if current numericChars make a valid dial code
  847. if (this.countryCodes[numericChars]) {
  848. // store the actual raw string (useful for matching later)
  849. dialCode = number.substr(0, i + 1);
  850. }
  851. // longest dial code is 4 chars
  852. if (numericChars.length == 4) {
  853. break;
  854. }
  855. }
  856. }
  857. }
  858. return dialCode;
  859. },
  860. // get the input val, adding the dial code if separateDialCode is enabled
  861. _getFullNumber: function() {
  862. 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
  863. normalizedVal = numericVal.charAt(0) == "1" ? numericVal : "1" + numericVal;
  864. if (this.options.separateDialCode) {
  865. prefix = "+" + dialCode;
  866. } else if (val.charAt(0) != "+" && val.charAt(0) != "1" && dialCode && dialCode.charAt(0) == "1" && dialCode.length == 4 && dialCode != normalizedVal.substr(0, 4)) {
  867. // if the user has entered a national NANP number, then ensure it includes the full dial code / area code
  868. prefix = dialCode.substr(1);
  869. } else {
  870. prefix = "";
  871. }
  872. return prefix + val;
  873. },
  874. // remove the dial code if separateDialCode is enabled
  875. _beforeSetNumber: function(number) {
  876. if (this.options.separateDialCode) {
  877. var dialCode = this._getDialCode(number);
  878. if (dialCode) {
  879. // US dialCode is "+1", which is what we want
  880. // CA dialCode is "+1 123", which is wrong - should be "+1" (as it has multiple area codes)
  881. // AS dialCode is "+1 684", which is what we want
  882. // Solution: if the country has area codes, then revert to just the dial code
  883. if (this.selectedCountryData.areaCodes !== null) {
  884. dialCode = "+" + this.selectedCountryData.dialCode;
  885. }
  886. // 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
  887. // NOTE: don't just trim all non-numerics as may want to preserve an open parenthesis etc
  888. var start = number[dialCode.length] === " " || number[dialCode.length] === "-" ? dialCode.length + 1 : dialCode.length;
  889. number = number.substr(start);
  890. }
  891. }
  892. return this._cap(number);
  893. },
  894. // trigger the 'countrychange' event
  895. _triggerCountryChange: function() {
  896. this.telInput.trigger("countrychange", this.selectedCountryData);
  897. },
  898. /**************************
  899. * SECRET PUBLIC METHODS
  900. **************************/
  901. // this is called when the geoip call returns
  902. handleAutoCountry: function() {
  903. if (this.options.initialCountry === "auto") {
  904. // 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
  905. this.defaultCountry = $.fn[pluginName].autoCountry;
  906. // if there's no initial value in the input, then update the flag
  907. if (!this.telInput.val()) {
  908. this.setCountry(this.defaultCountry);
  909. }
  910. this.autoCountryDeferred.resolve();
  911. }
  912. },
  913. // this is called when the utils request completes
  914. handleUtils: function() {
  915. // if the request was successful
  916. if (window.intlTelInputUtils) {
  917. // if there's an initial value in the input, then format it
  918. if (this.telInput.val()) {
  919. this._updateValFromNumber(this.telInput.val());
  920. }
  921. this._updatePlaceholder();
  922. }
  923. this.utilsScriptDeferred.resolve();
  924. },
  925. /********************
  926. * PUBLIC METHODS
  927. ********************/
  928. // remove plugin
  929. destroy: function() {
  930. if (this.allowDropdown) {
  931. // make sure the dropdown is closed (and unbind listeners)
  932. this._closeDropdown();
  933. // click event to open dropdown
  934. this.selectedFlagInner.parent().off(this.ns);
  935. // label click hack
  936. this.telInput.closest("label").off(this.ns);
  937. }
  938. // unbind submit event handler on form
  939. if (this.options.autoHideDialCode) {
  940. var form = this.telInput.prop("form");
  941. if (form) {
  942. $(form).off(this.ns);
  943. }
  944. }
  945. // unbind all events: key events, and focus/blur events if autoHideDialCode=true
  946. this.telInput.off(this.ns);
  947. // remove markup (but leave the original input)
  948. var container = this.telInput.parent();
  949. container.before(this.telInput).remove();
  950. },
  951. // get the extension from the current number
  952. getExtension: function() {
  953. if (window.intlTelInputUtils) {
  954. return intlTelInputUtils.getExtension(this._getFullNumber(), this.selectedCountryData.iso2);
  955. }
  956. return "";
  957. },
  958. // format the number to the given format
  959. getNumber: function(format) {
  960. if (window.intlTelInputUtils) {
  961. return intlTelInputUtils.formatNumber(this._getFullNumber(), this.selectedCountryData.iso2, format);
  962. }
  963. return "";
  964. },
  965. // get the type of the entered number e.g. landline/mobile
  966. getNumberType: function() {
  967. if (window.intlTelInputUtils) {
  968. return intlTelInputUtils.getNumberType(this._getFullNumber(), this.selectedCountryData.iso2);
  969. }
  970. return -99;
  971. },
  972. // get the country data for the currently selected flag
  973. getSelectedCountryData: function() {
  974. return this.selectedCountryData;
  975. },
  976. // get the validation error
  977. getValidationError: function() {
  978. if (window.intlTelInputUtils) {
  979. return intlTelInputUtils.getValidationError(this._getFullNumber(), this.selectedCountryData.iso2);
  980. }
  981. return -99;
  982. },
  983. // validate the input val - assumes the global function isValidNumber (from utilsScript)
  984. isValidNumber: function() {
  985. var val = $.trim(this._getFullNumber()), countryCode = this.options.nationalMode ? this.selectedCountryData.iso2 : "";
  986. return window.intlTelInputUtils ? intlTelInputUtils.isValidNumber(val, countryCode) : null;
  987. },
  988. // update the selected flag, and update the input val accordingly
  989. setCountry: function(countryCode) {
  990. countryCode = countryCode.toLowerCase();
  991. // check if already selected
  992. if (!this.selectedFlagInner.hasClass(countryCode)) {
  993. this._setFlag(countryCode);
  994. this._updateDialCode(this.selectedCountryData.dialCode, false);
  995. this._triggerCountryChange();
  996. }
  997. },
  998. // set the input value and update the flag
  999. setNumber: function(number) {
  1000. // we must update the flag first, which updates this.selectedCountryData, which is used for formatting the number before displaying it
  1001. var flagChanged = this._updateFlagFromNumber(number);
  1002. this._updateValFromNumber(number);
  1003. if (flagChanged) {
  1004. this._triggerCountryChange();
  1005. }
  1006. }
  1007. };
  1008. // using https://github.com/jquery-boilerplate/jquery-boilerplate/wiki/Extending-jQuery-Boilerplate
  1009. // (adapted to allow public functions)
  1010. $.fn[pluginName] = function(options) {
  1011. var args = arguments;
  1012. // Is the first parameter an object (options), or was omitted,
  1013. // instantiate a new instance of the plugin.
  1014. if (options === undefined || typeof options === "object") {
  1015. // collect all of the deferred objects for all instances created with this selector
  1016. var deferreds = [];
  1017. this.each(function() {
  1018. if (!$.data(this, "plugin_" + pluginName)) {
  1019. var instance = new Plugin(this, options);
  1020. var instanceDeferreds = instance._init();
  1021. // we now have 2 deffereds: 1 for auto country, 1 for utils script
  1022. deferreds.push(instanceDeferreds[0]);
  1023. deferreds.push(instanceDeferreds[1]);
  1024. $.data(this, "plugin_" + pluginName, instance);
  1025. }
  1026. });
  1027. // return the promise from the "master" deferred object that tracks all the others
  1028. return $.when.apply(null, deferreds);
  1029. } else if (typeof options === "string" && options[0] !== "_") {
  1030. // If the first parameter is a string and it doesn't start
  1031. // with an underscore or "contains" the `init`-function,
  1032. // treat this as a call to a public method.
  1033. // Cache the method call to make it possible to return a value
  1034. var returns;
  1035. this.each(function() {
  1036. var instance = $.data(this, "plugin_" + pluginName);
  1037. // Tests that there's already a plugin-instance
  1038. // and checks that the requested public method exists
  1039. if (instance instanceof Plugin && typeof instance[options] === "function") {
  1040. // Call the method of our plugin instance,
  1041. // and pass it the supplied arguments.
  1042. returns = instance[options].apply(instance, Array.prototype.slice.call(args, 1));
  1043. }
  1044. // Allow instances to be destroyed via the 'destroy' method
  1045. if (options === "destroy") {
  1046. $.data(this, "plugin_" + pluginName, null);
  1047. }
  1048. });
  1049. // If the earlier cached method gives a value back return the value,
  1050. // otherwise return this to preserve chainability.
  1051. return returns !== undefined ? returns : this;
  1052. }
  1053. };
  1054. /********************
  1055. * STATIC METHODS
  1056. ********************/
  1057. // get the country data object
  1058. $.fn[pluginName].getCountryData = function() {
  1059. return allCountries;
  1060. };
  1061. // load the utils script
  1062. $.fn[pluginName].loadUtils = function(path, utilsScriptDeferred) {
  1063. if (!$.fn[pluginName].loadedUtilsScript) {
  1064. // 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)
  1065. $.fn[pluginName].loadedUtilsScript = true;
  1066. // dont use $.getScript as it prevents caching
  1067. $.ajax({
  1068. type: "GET",
  1069. url: path,
  1070. complete: function() {
  1071. // tell all instances that the utils request is complete
  1072. $(".intl-tel-input input").intlTelInput("handleUtils");
  1073. },
  1074. dataType: "script",
  1075. cache: true
  1076. });
  1077. } else if (utilsScriptDeferred) {
  1078. utilsScriptDeferred.resolve();
  1079. }
  1080. };
  1081. // default options
  1082. $.fn[pluginName].defaults = defaults;
  1083. // version
  1084. $.fn[pluginName].version = "11.0.4";
  1085. // Array of country objects for the flag dropdown.
  1086. // Here is the criteria for the plugin to support a given country/territory
  1087. // - It has an iso2 code: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
  1088. // - It has a country calling code: https://en.wikipedia.org/wiki/List_of_country_calling_codes
  1089. // - It has a flag in the region-flags project: https://github.com/behdad/region-flags/tree/gh-pages/png
  1090. // - It is supported by libphonenumber (it must be listed here): https://github.com/googlei18n/libphonenumber/blob/master/resources/ShortNumberMetadata.xml
  1091. // Each country array has the following information:
  1092. // [
  1093. // Country name,
  1094. // iso2 code,
  1095. // International dial code,
  1096. // Order (if >1 country with same dial code),
  1097. // Area codes
  1098. // ]
  1099. 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 ] ];
  1100. // loop over all of the countries above
  1101. for (var i = 0; i < allCountries.length; i++) {
  1102. var c = allCountries[i];
  1103. allCountries[i] = {
  1104. name: c[0],
  1105. iso2: c[1],
  1106. dialCode: c[2],
  1107. priority: c[3] || 0,
  1108. areaCodes: c[4] || null
  1109. };
  1110. }
  1111. });