intl_phone_picker 0.0.7.1 → 0.0.7.2

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,1183 @@
1
+ //= require libphonenumber/utils
2
+
3
+ /*
4
+ International Telephone Input v6.0.4
5
+ https://github.com/Bluefieldscom/intl-tel-input.git
6
+ */
7
+ // wrap in UMD - see https://github.com/umdjs/umd/blob/master/jqueryPlugin.js
8
+ (function(factory) {
9
+ if (typeof define === "function" && define.amd) {
10
+ define([ "jquery" ], function($) {
11
+ factory($, window, document);
12
+ });
13
+ } else {
14
+ factory(jQuery, window, document);
15
+ }
16
+ })(function($, window, document, undefined) {
17
+ "use strict";
18
+ // these vars persist through all instances of the plugin
19
+ var pluginName = "intlTelInput", id = 1, // give each instance it's own id for namespaced event handling
20
+ defaults = {
21
+ // typing digits after a valid number will be added to the extension part of the number
22
+ allowExtensions: false,
23
+ // automatically format the number according to the selected country
24
+ autoFormat: true,
25
+ // if there is just a dial code in the input: remove it on blur, and re-add it on focus
26
+ autoHideDialCode: true,
27
+ // add or remove input placeholder with an example number for the selected country
28
+ autoPlaceholder: true,
29
+ // default country
30
+ defaultCountry: "",
31
+ // geoIp lookup function
32
+ geoIpLookup: null,
33
+ // don't insert international dial codes
34
+ nationalMode: true,
35
+ // number type to use for placeholders
36
+ numberType: "MOBILE",
37
+ // display only these countries
38
+ onlyCountries: [],
39
+ // the countries at the top of the list. defaults to united states and united kingdom
40
+ preferredCountries: [ "us", "gb" ],
41
+ // specify the path to the libphonenumber script to enable validation/formatting
42
+ utilsScript: ""
43
+ }, keys = {
44
+ UP: 38,
45
+ DOWN: 40,
46
+ ENTER: 13,
47
+ ESC: 27,
48
+ PLUS: 43,
49
+ A: 65,
50
+ Z: 90,
51
+ ZERO: 48,
52
+ NINE: 57,
53
+ SPACE: 32,
54
+ BSPACE: 8,
55
+ TAB: 9,
56
+ DEL: 46,
57
+ CTRL: 17,
58
+ CMD1: 91,
59
+ // Chrome
60
+ CMD2: 224
61
+ }, windowLoaded = false;
62
+ // keep track of if the window.load event has fired as impossible to check after the fact
63
+ $(window).load(function() {
64
+ windowLoaded = true;
65
+ });
66
+ function Plugin(element, options) {
67
+ this.element = element;
68
+ this.options = $.extend({}, defaults, options);
69
+ this._defaults = defaults;
70
+ // event namespace
71
+ this.ns = "." + pluginName + id++;
72
+ // Chrome, FF, Safari, IE9+
73
+ this.isGoodBrowser = Boolean(element.setSelectionRange);
74
+ this.hadInitialPlaceholder = Boolean($(element).attr("placeholder"));
75
+ this._name = pluginName;
76
+ }
77
+ Plugin.prototype = {
78
+ _init: function() {
79
+ // if in nationalMode, disable options relating to dial codes
80
+ if (this.options.nationalMode) {
81
+ this.options.autoHideDialCode = false;
82
+ }
83
+ // IE Mobile doesn't support the keypress event (see issue 68) which makes autoFormat impossible
84
+ if (navigator.userAgent.match(/IEMobile/i)) {
85
+ this.options.autoFormat = false;
86
+ }
87
+ // we cannot just test screen size as some smartphones/website meta tags will report desktop resolutions
88
+ // Note: for some reason jasmine fucks up if you put this in the main Plugin function with the rest of these declarations
89
+ // Note: to target Android Mobiles (and not Tablets), we must find "Android" and "Mobile"
90
+ this.isMobile = /Android.+Mobile|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
91
+ // we return these deferred objects from the _init() call so they can be watched, and then we resolve them when each specific request returns
92
+ // Note: again, jasmine had a spazz when I put these in the Plugin function
93
+ this.autoCountryDeferred = new $.Deferred();
94
+ this.utilsScriptDeferred = new $.Deferred();
95
+ // process all the data: onlyCountries, preferredCountries etc
96
+ this._processCountryData();
97
+ // generate the markup
98
+ this._generateMarkup();
99
+ // set the initial state of the input value and the selected flag
100
+ this._setInitialState();
101
+ // start all of the event listeners: autoHideDialCode, input keydown, selectedFlag click
102
+ this._initListeners();
103
+ // utils script, and auto country
104
+ this._initRequests();
105
+ // return the deferreds
106
+ return [ this.autoCountryDeferred, this.utilsScriptDeferred ];
107
+ },
108
+ /********************
109
+ * PRIVATE METHODS
110
+ ********************/
111
+ // prepare all of the country data, including onlyCountries and preferredCountries options
112
+ _processCountryData: function() {
113
+ // set the instances country data objects
114
+ this._setInstanceCountryData();
115
+ // set the preferredCountries property
116
+ this._setPreferredCountries();
117
+ },
118
+ // add a country code to this.countryCodes
119
+ _addCountryCode: function(iso2, dialCode, priority) {
120
+ if (!(dialCode in this.countryCodes)) {
121
+ this.countryCodes[dialCode] = [];
122
+ }
123
+ var index = priority || 0;
124
+ this.countryCodes[dialCode][index] = iso2;
125
+ },
126
+ // process onlyCountries array if present, and generate the countryCodes map
127
+ _setInstanceCountryData: function() {
128
+ var i;
129
+ // process onlyCountries option
130
+ if (this.options.onlyCountries.length) {
131
+ // standardise case
132
+ for (i = 0; i < this.options.onlyCountries.length; i++) {
133
+ this.options.onlyCountries[i] = this.options.onlyCountries[i].toLowerCase();
134
+ }
135
+ // build instance country array
136
+ this.countries = [];
137
+ for (i = 0; i < allCountries.length; i++) {
138
+ if ($.inArray(allCountries[i].iso2, this.options.onlyCountries) != -1) {
139
+ this.countries.push(allCountries[i]);
140
+ }
141
+ }
142
+ } else {
143
+ this.countries = allCountries;
144
+ }
145
+ // generate countryCodes map
146
+ this.countryCodes = {};
147
+ for (i = 0; i < this.countries.length; i++) {
148
+ var c = this.countries[i];
149
+ this._addCountryCode(c.iso2, c.dialCode, c.priority);
150
+ // area codes
151
+ if (c.areaCodes) {
152
+ for (var j = 0; j < c.areaCodes.length; j++) {
153
+ // full dial code is country code + dial code
154
+ this._addCountryCode(c.iso2, c.dialCode + c.areaCodes[j]);
155
+ }
156
+ }
157
+ }
158
+ },
159
+ // process preferred countries - iterate through the preferences,
160
+ // fetching the country data for each one
161
+ _setPreferredCountries: function() {
162
+ this.preferredCountries = [];
163
+ for (var i = 0; i < this.options.preferredCountries.length; i++) {
164
+ var countryCode = this.options.preferredCountries[i].toLowerCase(), countryData = this._getCountryData(countryCode, false, true);
165
+ if (countryData) {
166
+ this.preferredCountries.push(countryData);
167
+ }
168
+ }
169
+ },
170
+ // generate all of the markup for the plugin: the selected flag overlay, and the dropdown
171
+ _generateMarkup: function() {
172
+ // telephone input
173
+ this.telInput = $(this.element);
174
+ // 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)
175
+ this.telInput.attr("autocomplete", "off");
176
+ // containers (mostly for positioning)
177
+ this.telInput.wrap($("<div>", {
178
+ "class": "intl-tel-input"
179
+ }));
180
+ this.flagsContainer = $("<div>", {
181
+ "class": "flag-dropdown"
182
+ }).insertBefore(this.telInput);
183
+ // currently selected flag (displayed to left of input)
184
+ var selectedFlag = $("<div>", {
185
+ // make element focusable and tab naviagable
186
+ tabindex: "0",
187
+ "class": "selected-flag"
188
+ }).appendTo(this.flagsContainer);
189
+ this.selectedFlagInner = $("<div>", {
190
+ "class": "iti-flag"
191
+ }).appendTo(selectedFlag);
192
+ // CSS triangle
193
+ $("<div>", {
194
+ "class": "arrow"
195
+ }).appendTo(selectedFlag);
196
+ // country list
197
+ // mobile is just a native select element
198
+ // desktop is a proper list containing: preferred countries, then divider, then all countries
199
+ if (this.isMobile) {
200
+ this.countryList = $("<select>", {
201
+ "class": "iti-mobile-select"
202
+ }).appendTo(this.flagsContainer);
203
+ } else {
204
+ this.countryList = $("<ul>", {
205
+ "class": "country-list v-hide"
206
+ }).appendTo(this.flagsContainer);
207
+ if (this.preferredCountries.length && !this.isMobile) {
208
+ this._appendListItems(this.preferredCountries, "preferred");
209
+ $("<li>", {
210
+ "class": "divider"
211
+ }).appendTo(this.countryList);
212
+ }
213
+ }
214
+ this._appendListItems(this.countries, "");
215
+ if (!this.isMobile) {
216
+ // now we can grab the dropdown height, and hide it properly
217
+ this.dropdownHeight = this.countryList.outerHeight();
218
+ this.countryList.removeClass("v-hide").addClass("hide");
219
+ // this is useful in lots of places
220
+ this.countryListItems = this.countryList.children(".country");
221
+ }
222
+ },
223
+ // add a country <li> to the countryList <ul> container
224
+ // UPDATE: if isMobile, add an <option> to the countryList <select> container
225
+ _appendListItems: function(countries, className) {
226
+ // we create so many DOM elements, it is faster to build a temp string
227
+ // and then add everything to the DOM in one go at the end
228
+ var tmp = "";
229
+ // for each country
230
+ for (var i = 0; i < countries.length; i++) {
231
+ var c = countries[i];
232
+ if (this.isMobile) {
233
+ tmp += "<option data-dial-code='" + c.dialCode + "' value='" + c.iso2 + "'>";
234
+ tmp += c.name + " +" + c.dialCode;
235
+ tmp += "</option>";
236
+ } else {
237
+ // open the list item
238
+ tmp += "<li class='country " + className + "' data-dial-code='" + c.dialCode + "' data-country-code='" + c.iso2 + "'>";
239
+ // add the flag
240
+ tmp += "<div class='flag'><div class='iti-flag " + c.iso2 + "'></div></div>";
241
+ // and the country name and dial code
242
+ tmp += "<span class='country-name'>" + c.name + "</span>";
243
+ tmp += "<span class='dial-code'>+" + c.dialCode + "</span>";
244
+ // close the list item
245
+ tmp += "</li>";
246
+ }
247
+ }
248
+ this.countryList.append(tmp);
249
+ },
250
+ // set the initial state of the input value and the selected flag
251
+ _setInitialState: function() {
252
+ var val = this.telInput.val();
253
+ // if there is a number, and it's valid, we can go ahead and set the flag, else fall back to default
254
+ if (this._getDialCode(val)) {
255
+ this._updateFlagFromNumber(val, true);
256
+ } else if (this.options.defaultCountry != "auto") {
257
+ // check the defaultCountry option, else fall back to the first in the list
258
+ if (this.options.defaultCountry) {
259
+ this.options.defaultCountry = this._getCountryData(this.options.defaultCountry.toLowerCase(), false, false);
260
+ } else {
261
+ this.options.defaultCountry = this.preferredCountries.length ? this.preferredCountries[0] : this.countries[0];
262
+ }
263
+ this._selectFlag(this.options.defaultCountry.iso2);
264
+ // if empty, insert the default dial code (this function will check !nationalMode and !autoHideDialCode)
265
+ if (!val) {
266
+ this._updateDialCode(this.options.defaultCountry.dialCode, false);
267
+ }
268
+ }
269
+ // format
270
+ if (val) {
271
+ // this wont be run after _updateDialCode as that's only called if no val
272
+ this._updateVal(val);
273
+ }
274
+ },
275
+ // initialise the main event listeners: input keyup, and click selected flag
276
+ _initListeners: function() {
277
+ var that = this;
278
+ this._initKeyListeners();
279
+ // autoFormat prevents the change event from firing, so we need to check for changes between focus and blur in order to manually trigger it
280
+ if (this.options.autoHideDialCode || this.options.autoFormat) {
281
+ this._initFocusListeners();
282
+ }
283
+ if (this.isMobile) {
284
+ this.countryList.on("change" + this.ns, function(e) {
285
+ that._selectListItem($(this).find("option:selected"));
286
+ });
287
+ } else {
288
+ // 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
289
+ var label = this.telInput.closest("label");
290
+ if (label.length) {
291
+ label.on("click" + this.ns, function(e) {
292
+ // if the dropdown is closed, then focus the input, else ignore the click
293
+ if (that.countryList.hasClass("hide")) {
294
+ that.telInput.focus();
295
+ } else {
296
+ e.preventDefault();
297
+ }
298
+ });
299
+ }
300
+ // toggle country dropdown on click
301
+ var selectedFlag = this.selectedFlagInner.parent();
302
+ selectedFlag.on("click" + this.ns, function(e) {
303
+ // only intercept this event if we're opening the dropdown
304
+ // else let it bubble up to the top ("click-off-to-close" listener)
305
+ // we cannot just stopPropagation as it may be needed to close another instance
306
+ if (that.countryList.hasClass("hide") && !that.telInput.prop("disabled") && !that.telInput.prop("readonly")) {
307
+ that._showDropdown();
308
+ }
309
+ });
310
+ }
311
+ // open dropdown list if currently focused
312
+ this.flagsContainer.on("keydown" + that.ns, function(e) {
313
+ var isDropdownHidden = that.countryList.hasClass("hide");
314
+ if (isDropdownHidden && (e.which == keys.UP || e.which == keys.DOWN || e.which == keys.SPACE || e.which == keys.ENTER)) {
315
+ // prevent form from being submitted if "ENTER" was pressed
316
+ e.preventDefault();
317
+ // prevent event from being handled again by document
318
+ e.stopPropagation();
319
+ that._showDropdown();
320
+ }
321
+ // allow navigation from dropdown to input on TAB
322
+ if (e.which == keys.TAB) {
323
+ that._closeDropdown();
324
+ }
325
+ });
326
+ },
327
+ _initRequests: function() {
328
+ var that = this;
329
+ // if the user has specified the path to the utils script, fetch it on window.load
330
+ if (this.options.utilsScript) {
331
+ // if the plugin is being initialised after the window.load event has already been fired
332
+ if (windowLoaded) {
333
+ this.loadUtils();
334
+ } else {
335
+ // wait until the load event so we don't block any other requests e.g. the flags image
336
+ $(window).load(function() {
337
+ that.loadUtils();
338
+ });
339
+ }
340
+ } else {
341
+ this.utilsScriptDeferred.resolve();
342
+ }
343
+ if (this.options.defaultCountry == "auto") {
344
+ this._loadAutoCountry();
345
+ } else {
346
+ this.autoCountryDeferred.resolve();
347
+ }
348
+ },
349
+ _loadAutoCountry: function() {
350
+ var that = this;
351
+ // check for cookie
352
+ var cookieAutoCountry = $.cookie ? $.cookie("itiAutoCountry") : "";
353
+ if (cookieAutoCountry) {
354
+ $.fn[pluginName].autoCountry = cookieAutoCountry;
355
+ }
356
+ // 3 options:
357
+ // 1) already loaded (we're done)
358
+ // 2) not already started loading (start)
359
+ // 3) already started loading (do nothing - just wait for loading callback to fire)
360
+ if ($.fn[pluginName].autoCountry) {
361
+ this.autoCountryLoaded();
362
+ } else if (!$.fn[pluginName].startedLoadingAutoCountry) {
363
+ // don't do this twice!
364
+ $.fn[pluginName].startedLoadingAutoCountry = true;
365
+ if (typeof this.options.geoIpLookup === "function") {
366
+ this.options.geoIpLookup(function(countryCode) {
367
+ $.fn[pluginName].autoCountry = countryCode.toLowerCase();
368
+ if ($.cookie) {
369
+ $.cookie("itiAutoCountry", $.fn[pluginName].autoCountry, {
370
+ path: "/"
371
+ });
372
+ }
373
+ // tell all instances the auto country is ready
374
+ // TODO: this should just be the current instances
375
+ $(".intl-tel-input input").intlTelInput("autoCountryLoaded");
376
+ });
377
+ }
378
+ }
379
+ },
380
+ _initKeyListeners: function() {
381
+ var that = this;
382
+ if (this.options.autoFormat) {
383
+ // format number and update flag on keypress
384
+ // use keypress event as we want to ignore all input except for a select few keys,
385
+ // but we dont want to ignore the navigation keys like the arrows etc.
386
+ // NOTE: no point in refactoring this to only bind these listeners on focus/blur because then you would need to have those 2 listeners running the whole time anyway...
387
+ this.telInput.on("keypress" + this.ns, function(e) {
388
+ // 32 is space, and after that it's all chars (not meta/nav keys)
389
+ // this fix is needed for Firefox, which triggers keypress event for some meta/nav keys
390
+ // Update: also ignore if this is a metaKey e.g. FF and Safari trigger keypress on the v of Ctrl+v
391
+ // Update: also ignore if ctrlKey (FF on Windows/Ubuntu)
392
+ // Update: also check that we have utils before we do any autoFormat stuff
393
+ if (e.which >= keys.SPACE && !e.ctrlKey && !e.metaKey && window.intlTelInputUtils && !that.telInput.prop("readonly")) {
394
+ e.preventDefault();
395
+ // allowed keys are just numeric keys and plus
396
+ // we must allow plus for the case where the user does select-all and then hits plus to start typing a new number. we could refine this logic to first check that the selection contains a plus, but that wont work in old browsers, and I think it's overkill anyway
397
+ var isAllowedKey = e.which >= keys.ZERO && e.which <= keys.NINE || e.which == keys.PLUS, input = that.telInput[0], noSelection = that.isGoodBrowser && input.selectionStart == input.selectionEnd, max = that.telInput.attr("maxlength"), val = that.telInput.val(), // assumes that if max exists, it is >0
398
+ isBelowMax = max ? val.length < max : true;
399
+ // first: ensure we dont go over maxlength. we must do this here to prevent adding digits in the middle of the number
400
+ // still reformat even if not an allowed key as they could by typing a formatting char, but ignore if there's a selection as doesn't make sense to replace selection with illegal char and then immediately remove it
401
+ if (isBelowMax && (isAllowedKey || noSelection)) {
402
+ var newChar = isAllowedKey ? String.fromCharCode(e.which) : null;
403
+ that._handleInputKey(newChar, true, isAllowedKey);
404
+ // if something has changed, trigger the input event (which was otherwised squashed by the preventDefault)
405
+ if (val != that.telInput.val()) {
406
+ that.telInput.trigger("input");
407
+ }
408
+ }
409
+ if (!isAllowedKey) {
410
+ that._handleInvalidKey();
411
+ }
412
+ }
413
+ });
414
+ }
415
+ // handle cut/paste event (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.options.autoFormat && window.intlTelInputUtils) {
420
+ var cursorAtEnd = that.isGoodBrowser && that.telInput[0].selectionStart == that.telInput.val().length;
421
+ that._handleInputKey(null, cursorAtEnd);
422
+ that._ensurePlus();
423
+ } else {
424
+ // if no autoFormat, just update flag
425
+ that._updateFlagFromNumber(that.telInput.val());
426
+ }
427
+ });
428
+ });
429
+ // handle keyup event
430
+ // if autoFormat enabled: we use keyup to catch delete events (after the fact)
431
+ // if no autoFormat, this is used to update the flag
432
+ this.telInput.on("keyup" + this.ns, function(e) {
433
+ // the "enter" key event from selecting a dropdown item is triggered here on the input, because the document.keydown handler that initially handles that event triggers a focus on the input, and so the keyup for that same key event gets triggered here. weird, but just make sure we dont bother doing any re-formatting in this case (we've already done preventDefault in the keydown handler, so it wont actually submit the form or anything).
434
+ // ALSO: ignore keyup if readonly
435
+ if (e.which == keys.ENTER || that.telInput.prop("readonly")) {} else if (that.options.autoFormat && window.intlTelInputUtils) {
436
+ // cursorAtEnd defaults to false for bad browsers else they would never get a reformat on delete
437
+ var cursorAtEnd = that.isGoodBrowser && that.telInput[0].selectionStart == that.telInput.val().length;
438
+ if (!that.telInput.val()) {
439
+ // if they just cleared the input, update the flag to the default
440
+ that._updateFlagFromNumber("");
441
+ } else if (e.which == keys.DEL && !cursorAtEnd || e.which == keys.BSPACE) {
442
+ // if delete in the middle: reformat with no suffix (no need to reformat if delete at end)
443
+ // if backspace: reformat with no suffix (need to reformat if at end to remove any lingering suffix - this is a feature)
444
+ // important to remember never to add suffix on any delete key as can fuck up in ie8 so you can never delete a formatting char at the end
445
+ that._handleInputKey();
446
+ }
447
+ that._ensurePlus();
448
+ } else {
449
+ // if no autoFormat, just update flag
450
+ that._updateFlagFromNumber(that.telInput.val());
451
+ }
452
+ });
453
+ },
454
+ // prevent deleting the plus (if not in nationalMode)
455
+ _ensurePlus: function() {
456
+ if (!this.options.nationalMode) {
457
+ var val = this.telInput.val(), input = this.telInput[0];
458
+ if (val.charAt(0) != "+") {
459
+ // newCursorPos is current pos + 1 to account for the plus we are about to add
460
+ var newCursorPos = this.isGoodBrowser ? input.selectionStart + 1 : 0;
461
+ this.telInput.val("+" + val);
462
+ if (this.isGoodBrowser) {
463
+ input.setSelectionRange(newCursorPos, newCursorPos);
464
+ }
465
+ }
466
+ }
467
+ },
468
+ // alert the user to an invalid key event
469
+ _handleInvalidKey: function() {
470
+ var that = this;
471
+ this.telInput.trigger("invalidkey").addClass("iti-invalid-key");
472
+ setTimeout(function() {
473
+ that.telInput.removeClass("iti-invalid-key");
474
+ }, 100);
475
+ },
476
+ // when autoFormat is enabled: handle various key events on the input:
477
+ // 1) adding a new number character, which will replace any selection, reformat, and preserve the cursor position
478
+ // 2) reformatting on backspace/delete
479
+ // 3) cut/paste event
480
+ _handleInputKey: function(newNumericChar, addSuffix, isAllowedKey) {
481
+ var val = this.telInput.val(), cleanBefore = this._getClean(val), originalLeftChars, // raw DOM element
482
+ input = this.telInput[0], digitsOnRight = 0;
483
+ if (this.isGoodBrowser) {
484
+ // cursor strategy: maintain the number of digits on the right. we use the right instead of the left so that A) we dont have to account for the new digit (or multiple digits if paste event), and B) we're always on the right side of formatting suffixes
485
+ digitsOnRight = this._getDigitsOnRight(val, input.selectionEnd);
486
+ // if handling a new number character: insert it in the right place
487
+ if (newNumericChar) {
488
+ // replace any selection they may have made with the new char
489
+ val = val.substr(0, input.selectionStart) + newNumericChar + val.substring(input.selectionEnd, val.length);
490
+ } else {
491
+ // here we're not handling a new char, we're just doing a re-format (e.g. on delete/backspace/paste, after the fact), but we still need to maintain the cursor position. so make note of the char on the left, and then after the re-format, we'll count in the same number of digits from the right, and then keep going through any formatting chars until we hit the same left char that we had before.
492
+ // UPDATE: now have to store 2 chars as extensions formatting contains 2 spaces so you need to be able to distinguish
493
+ originalLeftChars = val.substr(input.selectionStart - 2, 2);
494
+ }
495
+ } else if (newNumericChar) {
496
+ val += newNumericChar;
497
+ }
498
+ // update the number and flag
499
+ this.setNumber(val, null, addSuffix, true, isAllowedKey);
500
+ // update the cursor position
501
+ if (this.isGoodBrowser) {
502
+ var newCursor;
503
+ val = this.telInput.val();
504
+ // if it was at the end, keep it there
505
+ if (!digitsOnRight) {
506
+ newCursor = val.length;
507
+ } else {
508
+ // else count in the same number of digits from the right
509
+ newCursor = this._getCursorFromDigitsOnRight(val, digitsOnRight);
510
+ // but if delete/paste etc, keep going left until hit the same left char as before
511
+ if (!newNumericChar) {
512
+ newCursor = this._getCursorFromLeftChar(val, newCursor, originalLeftChars);
513
+ }
514
+ }
515
+ // set the new cursor
516
+ input.setSelectionRange(newCursor, newCursor);
517
+ }
518
+ },
519
+ // we start from the position in guessCursor, and work our way left until we hit the originalLeftChars or a number to make sure that after reformatting the cursor has the same char on the left in the case of a delete etc
520
+ _getCursorFromLeftChar: function(val, guessCursor, originalLeftChars) {
521
+ for (var i = guessCursor; i > 0; i--) {
522
+ var leftChar = val.charAt(i - 1);
523
+ if ($.isNumeric(leftChar) || val.substr(i - 2, 2) == originalLeftChars) {
524
+ return i;
525
+ }
526
+ }
527
+ return 0;
528
+ },
529
+ // after a reformat we need to make sure there are still the same number of digits to the right of the cursor
530
+ _getCursorFromDigitsOnRight: function(val, digitsOnRight) {
531
+ for (var i = val.length - 1; i >= 0; i--) {
532
+ if ($.isNumeric(val.charAt(i))) {
533
+ if (--digitsOnRight === 0) {
534
+ return i;
535
+ }
536
+ }
537
+ }
538
+ return 0;
539
+ },
540
+ // get the number of numeric digits to the right of the cursor so we can reposition the cursor correctly after the reformat has happened
541
+ _getDigitsOnRight: function(val, selectionEnd) {
542
+ var digitsOnRight = 0;
543
+ for (var i = selectionEnd; i < val.length; i++) {
544
+ if ($.isNumeric(val.charAt(i))) {
545
+ digitsOnRight++;
546
+ }
547
+ }
548
+ return digitsOnRight;
549
+ },
550
+ // listen for focus and blur
551
+ _initFocusListeners: function() {
552
+ var that = this;
553
+ if (this.options.autoHideDialCode) {
554
+ // 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
555
+ this.telInput.on("mousedown" + this.ns, function(e) {
556
+ if (!that.telInput.is(":focus") && !that.telInput.val()) {
557
+ e.preventDefault();
558
+ // but this also cancels the focus, so we must trigger that manually
559
+ that.telInput.focus();
560
+ }
561
+ });
562
+ }
563
+ this.telInput.on("focus" + this.ns, function(e) {
564
+ var value = that.telInput.val();
565
+ // save this to compare on blur
566
+ that.telInput.data("focusVal", value);
567
+ // on focus: if empty, insert the dial code for the currently selected flag
568
+ if (that.options.autoHideDialCode && !value && !that.telInput.prop("readonly") && that.selectedCountryData.dialCode) {
569
+ that._updateVal("+" + that.selectedCountryData.dialCode, null, true);
570
+ // 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
571
+ that.telInput.one("keypress.plus" + that.ns, function(e) {
572
+ if (e.which == keys.PLUS) {
573
+ // if autoFormat is enabled, this key event will have already have been handled by another keypress listener (hence we need to add the "+"). if disabled, it will be handled after this by a keyup listener (hence no need to add the "+").
574
+ var newVal = that.options.autoFormat && window.intlTelInputUtils ? "+" : "";
575
+ that.telInput.val(newVal);
576
+ }
577
+ });
578
+ // 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
579
+ setTimeout(function() {
580
+ var input = that.telInput[0];
581
+ if (that.isGoodBrowser) {
582
+ var len = that.telInput.val().length;
583
+ input.setSelectionRange(len, len);
584
+ }
585
+ });
586
+ }
587
+ });
588
+ this.telInput.on("blur" + this.ns, function() {
589
+ if (that.options.autoHideDialCode) {
590
+ // on blur: if just a dial code then remove it
591
+ var value = that.telInput.val(), startsPlus = value.charAt(0) == "+";
592
+ if (startsPlus) {
593
+ var numeric = that._getNumeric(value);
594
+ // if just a plus, or if just a dial code
595
+ if (!numeric || that.selectedCountryData.dialCode == numeric) {
596
+ that.telInput.val("");
597
+ }
598
+ }
599
+ // remove the keypress listener we added on focus
600
+ that.telInput.off("keypress.plus" + that.ns);
601
+ }
602
+ // if autoFormat, we must manually trigger change event if value has changed
603
+ if (that.options.autoFormat && window.intlTelInputUtils && that.telInput.val() != that.telInput.data("focusVal")) {
604
+ that.telInput.trigger("change");
605
+ }
606
+ });
607
+ },
608
+ // extract the numeric digits from the given string
609
+ _getNumeric: function(s) {
610
+ return s.replace(/\D/g, "");
611
+ },
612
+ _getClean: function(s) {
613
+ var prefix = s.charAt(0) == "+" ? "+" : "";
614
+ return prefix + this._getNumeric(s);
615
+ },
616
+ // show the dropdown
617
+ _showDropdown: function() {
618
+ this._setDropdownPosition();
619
+ // update highlighting and scroll to active list item
620
+ var activeListItem = this.countryList.children(".active");
621
+ if (activeListItem.length) {
622
+ this._highlightListItem(activeListItem);
623
+ }
624
+ // show it
625
+ this.countryList.removeClass("hide");
626
+ if (activeListItem.length) {
627
+ this._scrollTo(activeListItem);
628
+ }
629
+ // bind all the dropdown-related listeners: mouseover, click, click-off, keydown
630
+ this._bindDropdownListeners();
631
+ // update the arrow
632
+ this.selectedFlagInner.children(".arrow").addClass("up");
633
+ },
634
+ // decide where to position dropdown (depends on position within viewport, and scroll)
635
+ _setDropdownPosition: function() {
636
+ var inputTop = this.telInput.offset().top, windowTop = $(window).scrollTop(), // dropdownFitsBelow = (dropdownBottom < windowBottom)
637
+ dropdownFitsBelow = inputTop + this.telInput.outerHeight() + this.dropdownHeight < windowTop + $(window).height(), dropdownFitsAbove = inputTop - this.dropdownHeight > windowTop;
638
+ // dropdownHeight - 1 for border
639
+ var cssTop = !dropdownFitsBelow && dropdownFitsAbove ? "-" + (this.dropdownHeight - 1) + "px" : "";
640
+ this.countryList.css("top", cssTop);
641
+ },
642
+ // we only bind dropdown listeners when the dropdown is open
643
+ _bindDropdownListeners: function() {
644
+ var that = this;
645
+ // when mouse over a list item, just highlight that one
646
+ // we add the class "highlight", so if they hit "enter" we know which one to select
647
+ this.countryList.on("mouseover" + this.ns, ".country", function(e) {
648
+ that._highlightListItem($(this));
649
+ });
650
+ // listen for country selection
651
+ this.countryList.on("click" + this.ns, ".country", function(e) {
652
+ that._selectListItem($(this));
653
+ });
654
+ // click off to close
655
+ // (except when this initial opening click is bubbling up)
656
+ // we cannot just stopPropagation as it may be needed to close another instance
657
+ var isOpening = true;
658
+ $("html").on("click" + this.ns, function(e) {
659
+ if (!isOpening) {
660
+ that._closeDropdown();
661
+ }
662
+ isOpening = false;
663
+ });
664
+ // listen for up/down scrolling, enter to select, or letters to jump to country name.
665
+ // use keydown as keypress doesn't fire for non-char keys and we want to catch if they
666
+ // just hit down and hold it to scroll down (no keyup event).
667
+ // listen on the document because that's where key events are triggered if no input has focus
668
+ var query = "", queryTimer = null;
669
+ $(document).on("keydown" + this.ns, function(e) {
670
+ // prevent down key from scrolling the whole page,
671
+ // and enter key from submitting a form etc
672
+ e.preventDefault();
673
+ if (e.which == keys.UP || e.which == keys.DOWN) {
674
+ // up and down to navigate
675
+ that._handleUpDownKey(e.which);
676
+ } else if (e.which == keys.ENTER) {
677
+ // enter to select
678
+ that._handleEnterKey();
679
+ } else if (e.which == keys.ESC) {
680
+ // esc to close
681
+ that._closeDropdown();
682
+ } else if (e.which >= keys.A && e.which <= keys.Z || e.which == keys.SPACE) {
683
+ // upper case letters (note: keyup/keydown only return upper case letters)
684
+ // jump to countries that start with the query string
685
+ if (queryTimer) {
686
+ clearTimeout(queryTimer);
687
+ }
688
+ query += String.fromCharCode(e.which);
689
+ that._searchForCountry(query);
690
+ // if the timer hits 1 second, reset the query
691
+ queryTimer = setTimeout(function() {
692
+ query = "";
693
+ }, 1e3);
694
+ }
695
+ });
696
+ },
697
+ // highlight the next/prev item in the list (and ensure it is visible)
698
+ _handleUpDownKey: function(key) {
699
+ var current = this.countryList.children(".highlight").first();
700
+ var next = key == keys.UP ? current.prev() : current.next();
701
+ if (next.length) {
702
+ // skip the divider
703
+ if (next.hasClass("divider")) {
704
+ next = key == keys.UP ? next.prev() : next.next();
705
+ }
706
+ this._highlightListItem(next);
707
+ this._scrollTo(next);
708
+ }
709
+ },
710
+ // select the currently highlighted item
711
+ _handleEnterKey: function() {
712
+ var currentCountry = this.countryList.children(".highlight").first();
713
+ if (currentCountry.length) {
714
+ this._selectListItem(currentCountry);
715
+ }
716
+ },
717
+ // find the first list item whose name starts with the query string
718
+ _searchForCountry: function(query) {
719
+ for (var i = 0; i < this.countries.length; i++) {
720
+ if (this._startsWith(this.countries[i].name, query)) {
721
+ var listItem = this.countryList.children("[data-country-code=" + this.countries[i].iso2 + "]").not(".preferred");
722
+ // update highlighting and scroll
723
+ this._highlightListItem(listItem);
724
+ this._scrollTo(listItem, true);
725
+ break;
726
+ }
727
+ }
728
+ },
729
+ // check if (uppercase) string a starts with string b
730
+ _startsWith: function(a, b) {
731
+ return a.substr(0, b.length).toUpperCase() == b;
732
+ },
733
+ // update the input's value to the given val
734
+ // if autoFormat=true, format it first according to the country-specific formatting rules
735
+ // Note: preventConversion will be false (i.e. we allow conversion) on init and when dev calls public method setNumber
736
+ _updateVal: function(val, format, addSuffix, preventConversion, isAllowedKey) {
737
+ var formatted;
738
+ if (this.options.autoFormat && window.intlTelInputUtils && this.selectedCountryData) {
739
+ if (typeof format == "number" && intlTelInputUtils.isValidNumber(val, this.selectedCountryData.iso2)) {
740
+ // if user specified a format, and it's a valid number, then format it accordingly
741
+ formatted = intlTelInputUtils.formatNumberByType(val, this.selectedCountryData.iso2, format);
742
+ } else if (!preventConversion && this.options.nationalMode && val.charAt(0) == "+" && intlTelInputUtils.isValidNumber(val, this.selectedCountryData.iso2)) {
743
+ // if nationalMode and we have a valid intl number, convert it to ntl
744
+ formatted = intlTelInputUtils.formatNumberByType(val, this.selectedCountryData.iso2, intlTelInputUtils.numberFormat.NATIONAL);
745
+ } else {
746
+ // else do the regular AsYouType formatting
747
+ formatted = intlTelInputUtils.formatNumber(val, this.selectedCountryData.iso2, addSuffix, this.options.allowExtensions, isAllowedKey);
748
+ }
749
+ // ensure we dont go over maxlength. we must do this here to truncate any formatting suffix, and also handle paste events
750
+ var max = this.telInput.attr("maxlength");
751
+ if (max && formatted.length > max) {
752
+ formatted = formatted.substr(0, max);
753
+ }
754
+ } else {
755
+ // no autoFormat, so just insert the original value
756
+ formatted = val;
757
+ }
758
+ this.telInput.val(formatted);
759
+ },
760
+ // check if need to select a new flag based on the given number
761
+ _updateFlagFromNumber: function(number, updateDefault) {
762
+ // if we're in nationalMode and we're on US/Canada, make sure the number starts with a +1 so _getDialCode will be able to extract the area code
763
+ // 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
764
+ if (number && this.options.nationalMode && this.selectedCountryData && this.selectedCountryData.dialCode == "1" && number.charAt(0) != "+") {
765
+ if (number.charAt(0) != "1") {
766
+ number = "1" + number;
767
+ }
768
+ number = "+" + number;
769
+ }
770
+ // try and extract valid dial code from input
771
+ var dialCode = this._getDialCode(number), countryCode = null;
772
+ if (dialCode) {
773
+ // check if one of the matching countries is already selected
774
+ var countryCodes = this.countryCodes[this._getNumeric(dialCode)], alreadySelected = this.selectedCountryData && $.inArray(this.selectedCountryData.iso2, countryCodes) != -1;
775
+ // if a matching country is not already selected (or this is an unknown NANP area code): choose the first in the list
776
+ if (!alreadySelected || this._isUnknownNanp(number, dialCode)) {
777
+ // if using onlyCountries option, countryCodes[0] may be empty, so we must find the first non-empty index
778
+ for (var j = 0; j < countryCodes.length; j++) {
779
+ if (countryCodes[j]) {
780
+ countryCode = countryCodes[j];
781
+ break;
782
+ }
783
+ }
784
+ }
785
+ } else if (number.charAt(0) == "+" && this._getNumeric(number).length) {
786
+ // invalid dial code, so empty
787
+ // Note: use getNumeric here because the number has not been formatted yet, so could contain bad shit
788
+ countryCode = "";
789
+ } else if (!number || number == "+") {
790
+ // empty, or just a plus, so default
791
+ countryCode = this.options.defaultCountry.iso2;
792
+ }
793
+ if (countryCode !== null) {
794
+ this._selectFlag(countryCode, updateDefault);
795
+ }
796
+ },
797
+ // check if the given number contains an unknown area code from the North American Numbering Plan i.e. the only dialCode that could be extracted was +1 but the actual number's length is >=4
798
+ _isUnknownNanp: function(number, dialCode) {
799
+ return dialCode == "+1" && this._getNumeric(number).length >= 4;
800
+ },
801
+ // remove highlighting from other list items and highlight the given item
802
+ _highlightListItem: function(listItem) {
803
+ this.countryListItems.removeClass("highlight");
804
+ listItem.addClass("highlight");
805
+ },
806
+ // find the country data for the given country code
807
+ // the ignoreOnlyCountriesOption is only used during init() while parsing the onlyCountries array
808
+ _getCountryData: function(countryCode, ignoreOnlyCountriesOption, allowFail) {
809
+ var countryList = ignoreOnlyCountriesOption ? allCountries : this.countries;
810
+ for (var i = 0; i < countryList.length; i++) {
811
+ if (countryList[i].iso2 == countryCode) {
812
+ return countryList[i];
813
+ }
814
+ }
815
+ if (allowFail) {
816
+ return null;
817
+ } else {
818
+ throw new Error("No country data for '" + countryCode + "'");
819
+ }
820
+ },
821
+ // select the given flag, update the placeholder and the active list item
822
+ _selectFlag: function(countryCode, updateDefault) {
823
+ // do this first as it will throw an error and stop if countryCode is invalid
824
+ this.selectedCountryData = countryCode ? this._getCountryData(countryCode, false, false) : {};
825
+ // update the "defaultCountry" - we only need the iso2 from now on, so just store that
826
+ if (updateDefault && this.selectedCountryData.iso2) {
827
+ // can't just make this equal to selectedCountryData as would be a ref to that object
828
+ this.options.defaultCountry = {
829
+ iso2: this.selectedCountryData.iso2
830
+ };
831
+ }
832
+ this.selectedFlagInner.attr("class", "iti-flag " + countryCode);
833
+ // update the selected country's title attribute
834
+ var title = countryCode ? this.selectedCountryData.name + ": +" + this.selectedCountryData.dialCode : "Unknown";
835
+ this.selectedFlagInner.parent().attr("title", title);
836
+ // and the input's placeholder
837
+ this._updatePlaceholder();
838
+ if (this.isMobile) {
839
+ this.countryList.val(countryCode);
840
+ } else {
841
+ // update the active list item
842
+ this.countryListItems.removeClass("active");
843
+ if (countryCode) {
844
+ this.countryListItems.find(".iti-flag." + countryCode).first().closest(".country").addClass("active");
845
+ }
846
+ }
847
+ },
848
+ // update the input placeholder to an example number from the currently selected country
849
+ _updatePlaceholder: function() {
850
+ if (window.intlTelInputUtils && !this.hadInitialPlaceholder && this.options.autoPlaceholder && this.selectedCountryData) {
851
+ var iso2 = this.selectedCountryData.iso2, numberType = intlTelInputUtils.numberType[this.options.numberType || "FIXED_LINE"], placeholder = iso2 ? intlTelInputUtils.getExampleNumber(iso2, this.options.nationalMode, numberType) : "";
852
+ this.telInput.attr("placeholder", placeholder);
853
+ }
854
+ },
855
+ // called when the user selects a list item from the dropdown
856
+ _selectListItem: function(listItem) {
857
+ var countryCodeAttr = this.isMobile ? "value" : "data-country-code";
858
+ // update selected flag and active list item
859
+ this._selectFlag(listItem.attr(countryCodeAttr), true);
860
+ if (!this.isMobile) {
861
+ this._closeDropdown();
862
+ }
863
+ this._updateDialCode(listItem.attr("data-dial-code"), true);
864
+ // always fire the change event as even if nationalMode=true (and we haven't updated the input val), the system as a whole has still changed - see country-sync example. think of it as making a selection from a select element.
865
+ this.telInput.trigger("change");
866
+ // focus the input
867
+ this.telInput.focus();
868
+ // fix 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
869
+ if (this.isGoodBrowser) {
870
+ var len = this.telInput.val().length;
871
+ this.telInput[0].setSelectionRange(len, len);
872
+ }
873
+ },
874
+ // close the dropdown and unbind any listeners
875
+ _closeDropdown: function() {
876
+ this.countryList.addClass("hide");
877
+ // update the arrow
878
+ this.selectedFlagInner.children(".arrow").removeClass("up");
879
+ // unbind key events
880
+ $(document).off(this.ns);
881
+ // unbind click-off-to-close
882
+ $("html").off(this.ns);
883
+ // unbind hover and click listeners
884
+ this.countryList.off(this.ns);
885
+ },
886
+ // check if an element is visible within it's container, else scroll until it is
887
+ _scrollTo: function(element, middle) {
888
+ 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;
889
+ if (elementTop < containerTop) {
890
+ // scroll up
891
+ if (middle) {
892
+ newScrollTop -= middleOffset;
893
+ }
894
+ container.scrollTop(newScrollTop);
895
+ } else if (elementBottom > containerBottom) {
896
+ // scroll down
897
+ if (middle) {
898
+ newScrollTop += middleOffset;
899
+ }
900
+ var heightDifference = containerHeight - elementHeight;
901
+ container.scrollTop(newScrollTop - heightDifference);
902
+ }
903
+ },
904
+ // replace any existing dial code with the new one (if not in nationalMode)
905
+ // also we need to know if we're focusing for a couple of reasons e.g. if so, we want to add any formatting suffix, also if the input is empty and we're not in nationalMode, then we want to insert the dial code
906
+ _updateDialCode: function(newDialCode, focusing) {
907
+ var inputVal = this.telInput.val(), newNumber;
908
+ // save having to pass this every time
909
+ newDialCode = "+" + newDialCode;
910
+ if (this.options.nationalMode && inputVal.charAt(0) != "+") {
911
+ // if nationalMode, we just want to re-format
912
+ newNumber = inputVal;
913
+ } else if (inputVal) {
914
+ // if the previous number contained a valid dial code, replace it
915
+ // (if more than just a plus character)
916
+ var prevDialCode = this._getDialCode(inputVal);
917
+ if (prevDialCode.length > 1) {
918
+ newNumber = inputVal.replace(prevDialCode, newDialCode);
919
+ } else {
920
+ // if the previous number didn't contain a dial code, we should persist it
921
+ var existingNumber = inputVal.charAt(0) != "+" ? $.trim(inputVal) : "";
922
+ newNumber = newDialCode + existingNumber;
923
+ }
924
+ } else {
925
+ newNumber = !this.options.autoHideDialCode || focusing ? newDialCode : "";
926
+ }
927
+ this._updateVal(newNumber, null, focusing);
928
+ },
929
+ // try and extract a valid international dial code from a full telephone number
930
+ // Note: returns the raw string inc plus character and any whitespace/dots etc
931
+ _getDialCode: function(number) {
932
+ var dialCode = "";
933
+ // only interested in international numbers (starting with a plus)
934
+ if (number.charAt(0) == "+") {
935
+ var numericChars = "";
936
+ // iterate over chars
937
+ for (var i = 0; i < number.length; i++) {
938
+ var c = number.charAt(i);
939
+ // if char is number
940
+ if ($.isNumeric(c)) {
941
+ numericChars += c;
942
+ // if current numericChars make a valid dial code
943
+ if (this.countryCodes[numericChars]) {
944
+ // store the actual raw string (useful for matching later)
945
+ dialCode = number.substr(0, i + 1);
946
+ }
947
+ // longest dial code is 4 chars
948
+ if (numericChars.length == 4) {
949
+ break;
950
+ }
951
+ }
952
+ }
953
+ }
954
+ return dialCode;
955
+ },
956
+ /********************
957
+ * PUBLIC METHODS
958
+ ********************/
959
+ // this is called when the geoip call returns
960
+ autoCountryLoaded: function() {
961
+ if (this.options.defaultCountry == "auto") {
962
+ this.options.defaultCountry = $.fn[pluginName].autoCountry;
963
+ this._setInitialState();
964
+ this.autoCountryDeferred.resolve();
965
+ }
966
+ },
967
+ // remove plugin
968
+ destroy: function() {
969
+ if (!this.isMobile) {
970
+ // make sure the dropdown is closed (and unbind listeners)
971
+ this._closeDropdown();
972
+ }
973
+ // key events, and focus/blur events if autoHideDialCode=true
974
+ this.telInput.off(this.ns);
975
+ if (this.isMobile) {
976
+ // change event on select country
977
+ this.countryList.off(this.ns);
978
+ } else {
979
+ // click event to open dropdown
980
+ this.selectedFlagInner.parent().off(this.ns);
981
+ // label click hack
982
+ this.telInput.closest("label").off(this.ns);
983
+ }
984
+ // remove markup
985
+ var container = this.telInput.parent();
986
+ container.before(this.telInput).remove();
987
+ },
988
+ // extract the phone number extension if present
989
+ getExtension: function() {
990
+ return this.telInput.val().split(" ext. ")[1] || "";
991
+ },
992
+ // format the number to the given type
993
+ getNumber: function(type) {
994
+ if (window.intlTelInputUtils) {
995
+ return intlTelInputUtils.formatNumberByType(this.telInput.val(), this.selectedCountryData.iso2, type);
996
+ }
997
+ return "";
998
+ },
999
+ // get the type of the entered number e.g. landline/mobile
1000
+ getNumberType: function() {
1001
+ if (window.intlTelInputUtils) {
1002
+ return intlTelInputUtils.getNumberType(this.telInput.val(), this.selectedCountryData.iso2);
1003
+ }
1004
+ return -99;
1005
+ },
1006
+ // get the country data for the currently selected flag
1007
+ getSelectedCountryData: function() {
1008
+ // if this is undefined, the plugin will return it's instance instead, so in that case an empty object makes more sense
1009
+ return this.selectedCountryData || {};
1010
+ },
1011
+ // get the validation error
1012
+ getValidationError: function() {
1013
+ if (window.intlTelInputUtils) {
1014
+ return intlTelInputUtils.getValidationError(this.telInput.val(), this.selectedCountryData.iso2);
1015
+ }
1016
+ return -99;
1017
+ },
1018
+ // validate the input val - assumes the global function isValidNumber (from utilsScript)
1019
+ isValidNumber: function() {
1020
+ var val = $.trim(this.telInput.val()), countryCode = this.options.nationalMode ? this.selectedCountryData.iso2 : "";
1021
+ if (window.intlTelInputUtils) {
1022
+ return intlTelInputUtils.isValidNumber(val, countryCode);
1023
+ }
1024
+ return false;
1025
+ },
1026
+ // load the utils script
1027
+ loadUtils: function(path) {
1028
+ var that = this;
1029
+ var utilsScript = path || this.options.utilsScript;
1030
+ if (!$.fn[pluginName].loadedUtilsScript && utilsScript) {
1031
+ // don't do this twice! (dont just check if the global intlTelInputUtils exists as if init plugin multiple times in quick succession, it may not have finished loading yet)
1032
+ $.fn[pluginName].loadedUtilsScript = true;
1033
+ // dont use $.getScript as it prevents caching
1034
+ $.ajax({
1035
+ url: utilsScript,
1036
+ success: function() {
1037
+ // tell all instances the utils are ready
1038
+ $(".intl-tel-input input").intlTelInput("utilsLoaded");
1039
+ },
1040
+ complete: function() {
1041
+ that.utilsScriptDeferred.resolve();
1042
+ },
1043
+ dataType: "script",
1044
+ cache: true
1045
+ });
1046
+ } else {
1047
+ this.utilsScriptDeferred.resolve();
1048
+ }
1049
+ },
1050
+ // update the selected flag, and update the input val accordingly
1051
+ selectCountry: function(countryCode) {
1052
+ countryCode = countryCode.toLowerCase();
1053
+ // check if already selected
1054
+ if (!this.selectedFlagInner.hasClass(countryCode)) {
1055
+ this._selectFlag(countryCode, true);
1056
+ this._updateDialCode(this.selectedCountryData.dialCode, false);
1057
+ }
1058
+ },
1059
+ // set the input value and update the flag
1060
+ setNumber: function(number, format, addSuffix, preventConversion, isAllowedKey) {
1061
+ // ensure starts with plus
1062
+ if (!this.options.nationalMode && number.charAt(0) != "+") {
1063
+ number = "+" + number;
1064
+ }
1065
+ // we must update the flag first, which updates this.selectedCountryData, which is used later for formatting the number before displaying it
1066
+ this._updateFlagFromNumber(number);
1067
+ this._updateVal(number, format, addSuffix, preventConversion, isAllowedKey);
1068
+ },
1069
+ // this is called when the utils are ready
1070
+ utilsLoaded: function() {
1071
+ // if autoFormat is enabled and there's an initial value in the input, then format it
1072
+ if (this.options.autoFormat && this.telInput.val()) {
1073
+ this._updateVal(this.telInput.val());
1074
+ }
1075
+ this._updatePlaceholder();
1076
+ }
1077
+ };
1078
+ // adapted to allow public functions
1079
+ // using https://github.com/jquery-boilerplate/jquery-boilerplate/wiki/Extending-jQuery-Boilerplate
1080
+ $.fn[pluginName] = function(options) {
1081
+ var args = arguments;
1082
+ // Is the first parameter an object (options), or was omitted,
1083
+ // instantiate a new instance of the plugin.
1084
+ if (options === undefined || typeof options === "object") {
1085
+ var deferreds = [];
1086
+ this.each(function() {
1087
+ if (!$.data(this, "plugin_" + pluginName)) {
1088
+ var instance = new Plugin(this, options);
1089
+ var instanceDeferreds = instance._init();
1090
+ // we now have 2 deffereds: 1 for auto country, 1 for utils script
1091
+ deferreds.push(instanceDeferreds[0]);
1092
+ deferreds.push(instanceDeferreds[1]);
1093
+ $.data(this, "plugin_" + pluginName, instance);
1094
+ }
1095
+ });
1096
+ // return the promise from the "master" deferred object that tracks all the others
1097
+ return $.when.apply(null, deferreds);
1098
+ } else if (typeof options === "string" && options[0] !== "_") {
1099
+ // If the first parameter is a string and it doesn't start
1100
+ // with an underscore or "contains" the `init`-function,
1101
+ // treat this as a call to a public method.
1102
+ // Cache the method call to make it possible to return a value
1103
+ var returns;
1104
+ this.each(function() {
1105
+ var instance = $.data(this, "plugin_" + pluginName);
1106
+ // Tests that there's already a plugin-instance
1107
+ // and checks that the requested public method exists
1108
+ if (instance instanceof Plugin && typeof instance[options] === "function") {
1109
+ // Call the method of our plugin instance,
1110
+ // and pass it the supplied arguments.
1111
+ returns = instance[options].apply(instance, Array.prototype.slice.call(args, 1));
1112
+ }
1113
+ // Allow instances to be destroyed via the 'destroy' method
1114
+ if (options === "destroy") {
1115
+ $.data(this, "plugin_" + pluginName, null);
1116
+ }
1117
+ });
1118
+ // If the earlier cached method gives a value back return the value,
1119
+ // otherwise return this to preserve chainability.
1120
+ return returns !== undefined ? returns : this;
1121
+ }
1122
+ };
1123
+ /********************
1124
+ * STATIC METHODS
1125
+ ********************/
1126
+ // get the country data object
1127
+ $.fn[pluginName].getCountryData = function() {
1128
+ return allCountries;
1129
+ };
1130
+ $.fn[pluginName].version = "6.0.4";
1131
+ // Tell JSHint to ignore this warning: "character may get silently deleted by one or more browsers"
1132
+ // jshint -W100
1133
+ // Array of country objects for the flag dropdown.
1134
+ // Each contains a name, country code (ISO 3166-1 alpha-2) and dial code.
1135
+ // Originally from https://github.com/mledoze/countries
1136
+ // then modified using the following JavaScript (NOW OUT OF DATE):
1137
+ /*
1138
+ var result = [];
1139
+ _.each(countries, function(c) {
1140
+ // ignore countries without a dial code
1141
+ if (c.callingCode[0].length) {
1142
+ result.push({
1143
+ // var locals contains country names with localised versions in brackets
1144
+ n: _.findWhere(locals, {
1145
+ countryCode: c.cca2
1146
+ }).name,
1147
+ i: c.cca2.toLowerCase(),
1148
+ d: c.callingCode[0]
1149
+ });
1150
+ }
1151
+ });
1152
+ JSON.stringify(result);
1153
+ */
1154
+ // then with a couple of manual re-arrangements to be alphabetical
1155
+ // then changed Kazakhstan from +76 to +7
1156
+ // and Vatican City from +379 to +39 (see issue 50)
1157
+ // and Caribean Netherlands from +5997 to +599
1158
+ // and Curacao from +5999 to +599
1159
+ // Removed: Åland Islands, Christmas Island, Cocos Islands, Guernsey, Isle of Man, Jersey, Kosovo, Mayotte, Pitcairn Islands, South Georgia, Svalbard, Western Sahara
1160
+ // Update: converted objects to arrays to save bytes!
1161
+ // Update: added "priority" for countries with the same dialCode as others
1162
+ // Update: added array of area codes for countries with the same dialCode as others
1163
+ // So each country array has the following information:
1164
+ // [
1165
+ // Country name,
1166
+ // iso2 code,
1167
+ // International dial code,
1168
+ // Order (if >1 country with same dial code),
1169
+ // Area codes (if >1 country with same dial code)
1170
+ // ]
1171
+ 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" ], [ "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" ], [ "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" ], [ "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" ], [ "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" ], [ "Israel (‫ישראל‬‎)", "il", "972" ], [ "Italy (Italia)", "it", "39", 0 ], [ "Jamaica", "jm", "1876" ], [ "Japan (日本)", "jp", "81" ], [ "Jordan (‫الأردن‬‎)", "jo", "962" ], [ "Kazakhstan (Казахстан)", "kz", "7", 1 ], [ "Kenya", "ke", "254" ], [ "Kiribati", "ki", "686" ], [ "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" ], [ "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" ], [ "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" ], [ "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" ], [ "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" ], [ "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" ], [ "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" ], [ "Yemen (‫اليمن‬‎)", "ye", "967" ], [ "Zambia", "zm", "260" ], [ "Zimbabwe", "zw", "263" ] ];
1172
+ // loop over all of the countries above
1173
+ for (var i = 0; i < allCountries.length; i++) {
1174
+ var c = allCountries[i];
1175
+ allCountries[i] = {
1176
+ name: c[0],
1177
+ iso2: c[1],
1178
+ dialCode: c[2],
1179
+ priority: c[3] || 0,
1180
+ areaCodes: c[4] || null
1181
+ };
1182
+ }
1183
+ });