rails-intl-tel-input 0.1.2

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: c444fccdf72a8770e91a97e49678c1729cea8bf9
4
+ data.tar.gz: cbf385b96e2ff0a7b4ee220eee9319bd90e2290b
5
+ SHA512:
6
+ metadata.gz: c017a16ac76361e42735e45c6f5f1fc72874757645ba0321d8942a61086bbc5dad5e03cdb7254232dfc5ca9dc74e000f942acf7eee19cc14b8fa8b7b4ade7f7c
7
+ data.tar.gz: f69fa5e70ba971939f4ce7058ced4bcd11bd4a842bc23ba493d462eee795d14cb9e5e602bc560fd44bb07cb4eac373352aee933f537537d8c76ce19d1d4127d7
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
data/.rspec ADDED
@@ -0,0 +1 @@
1
+ --color
@@ -0,0 +1,11 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.3.0
4
+ - 2.2.4
5
+ - 2.1.9
6
+ before_install: gem install bundler
7
+ branches:
8
+ only:
9
+ - master
10
+ env:
11
+ - COVERALLS=1
@@ -0,0 +1,7 @@
1
+ # v0.1.2 / 2016-05-07
2
+
3
+ Fixed JavaScript error
4
+
5
+ # v0.1.0 / 2016-05-06
6
+
7
+ Created project
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in rails-intl-tel-input.gemspec
4
+ gemspec
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 Chen, Yi-Cyuan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,61 @@
1
+ # rails-intl-tel-input
2
+
3
+ [![Build Status](https://api.travis-ci.org/emn178/rails-intl-tel-input.png)](https://travis-ci.org/emn178/rails-intl-tel-input)
4
+ [![Coverage Status](https://coveralls.io/repos/emn178/rails-intl-tel-input/badge.svg?branch=master)](https://coveralls.io/r/emn178/rails-intl-tel-input?branch=master)
5
+
6
+ Integrate with [intl-tel-input](https://github.com/jackocnr/intl-tel-input) to provide international telephone numbers input and form helper.
7
+
8
+ ## Installation
9
+
10
+ Add this line to your application's Gemfile:
11
+
12
+ ```ruby
13
+ gem 'rails-intl-tel-input'
14
+ ```
15
+
16
+ And then execute:
17
+
18
+ bundle
19
+
20
+ Or install it yourself as:
21
+
22
+ gem install rails-intl-tel-input
23
+
24
+ ## Usage
25
+
26
+ ### Require Javascript
27
+ Make sure you required **jQuery** and add the following to /app/assets/javascripts/application.js:
28
+ ```JavaScript
29
+ //= require intlTelInput
30
+ ```
31
+ ### Require CSS
32
+ Add the following to /app/assets/stylesheets/application.css:
33
+ ```CSS
34
+ /*
35
+ *= require intlTelInput
36
+ */
37
+ ```
38
+
39
+ ### Helpers
40
+ You can use `intl_tel_input_tag` and `intl_tel_input`.
41
+ ```ERB
42
+ <%= intl_tel_input_tag(name, value, intl_tel_input_options, html_options) %>
43
+ <%= intl_tel_input_tag(:tel, 'red', {:allowDropdown => false}, {:class => 'tel'}) %>
44
+ <%= intl_tel_input_tag(:tel) %>
45
+
46
+ or form builder
47
+
48
+ <% form_for @item do |f| %>
49
+ <%= f.intl_tel_input(method, intl_tel_input_options, html_options) %>
50
+ <%= f.intl_tel_input(:tel, {:allowDropdown => false}, {:class => 'tel'}) %>
51
+ <%= f.intl_tel_input(:tel) %>
52
+ <% end %>
53
+ ```
54
+
55
+ ## License
56
+
57
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
58
+
59
+ ## Contact
60
+ The project's website is located at https://github.com/emn178/rails-intl-tel-input
61
+ Author: Chen, Yi-Cyuan (emn178@gmail.com)
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
@@ -0,0 +1,20 @@
1
+ //= require intlTelInput/intlTelInput
2
+ //= require intlTelInput/utils
3
+
4
+ (function ($) {
5
+ $(document).on('ready page:load', function () {
6
+ $('[data-intl-tel-input]').each(function () {
7
+ var element = $(this);
8
+ var hidden = $('<input type="hidden"/>')
9
+ .attr('name', element.attr('name'))
10
+ .val(element.val())
11
+ .insertAfter(element);
12
+ element.intlTelInput(element.data('intl-tel-input') || {});
13
+
14
+ element.removeAttr('name')
15
+ .closest('form').submit(function () {
16
+ hidden.val(element.intlTelInput('getNumber'));
17
+ });
18
+ });
19
+ });
20
+ })(jQuery);
@@ -0,0 +1,1120 @@
1
+ /*
2
+ * International Telephone Input v8.5.2
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 or remove input placeholder with an example number for the selected country
27
+ autoPlaceholder: true,
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
35
+ formatOnInit: true,
36
+ // geoIp lookup function
37
+ geoIpLookup: null,
38
+ // initial country
39
+ initialCountry: "",
40
+ // don't insert international dial codes
41
+ nationalMode: true,
42
+ // number type to use for placeholders
43
+ numberType: "MOBILE",
44
+ // display only these countries
45
+ onlyCountries: [],
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
+ };
63
+ // keep track of if the window.load event has fired as impossible to check after the fact
64
+ $(window).load(function() {
65
+ // UPDATE: use a public static field so we can fudge it in the tests
66
+ $.fn[pluginName].windowLoaded = true;
67
+ });
68
+ function Plugin(element, options) {
69
+ this.telInput = $(element);
70
+ this.options = $.extend({}, defaults, options);
71
+ // event namespace
72
+ this.ns = "." + pluginName + id++;
73
+ // Chrome, FF, Safari, IE9+
74
+ this.isGoodBrowser = Boolean(element.setSelectionRange);
75
+ this.hadInitialPlaceholder = Boolean($(element).attr("placeholder"));
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
+ // 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)
84
+ if (this.options.separateDialCode) {
85
+ this.options.autoHideDialCode = this.options.nationalMode = false;
86
+ // let's force this for now for simplicity - we can support this later if need be
87
+ this.options.allowDropdown = true;
88
+ }
89
+ // we cannot just test screen size as some smartphones/website meta tags will report desktop resolutions
90
+ // Note: for some reason jasmine breaks if you put this in the main Plugin function with the rest of these declarations
91
+ // Note: to target Android Mobiles (and not Tablets), we must find "Android" and "Mobile"
92
+ this.isMobile = /Android.+Mobile|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
93
+ if (this.isMobile) {
94
+ // trigger the mobile dropdown css
95
+ $("body").addClass("iti-mobile");
96
+ // on mobile, we want a full screen dropdown, so we must append it to the body
97
+ if (!this.options.dropdownContainer) {
98
+ this.options.dropdownContainer = "body";
99
+ }
100
+ }
101
+ // we return these deferred objects from the _init() call so they can be watched, and then we resolve them when each specific request returns
102
+ // Note: again, jasmine breaks when I put these in the Plugin function
103
+ this.autoCountryDeferred = new $.Deferred();
104
+ this.utilsScriptDeferred = new $.Deferred();
105
+ // process all the data: onlyCountries, excludeCountries, preferredCountries etc
106
+ this._processCountryData();
107
+ // generate the markup
108
+ this._generateMarkup();
109
+ // set the initial state of the input value and the selected flag
110
+ this._setInitialState();
111
+ // start all of the event listeners: autoHideDialCode, input keydown, selectedFlag click
112
+ this._initListeners();
113
+ // utils script, and auto country
114
+ this._initRequests();
115
+ // return the deferreds
116
+ return [ this.autoCountryDeferred, this.utilsScriptDeferred ];
117
+ },
118
+ /********************
119
+ * PRIVATE METHODS
120
+ ********************/
121
+ // prepare all of the country data, including onlyCountries, excludeCountries and preferredCountries options
122
+ _processCountryData: function() {
123
+ // process onlyCountries or excludeCountries array if present
124
+ this._processAllCountries();
125
+ // process the countryCodes map
126
+ this._processCountryCodes();
127
+ // process the preferredCountries
128
+ this._processPreferredCountries();
129
+ },
130
+ // add a country code to this.countryCodes
131
+ _addCountryCode: function(iso2, dialCode, priority) {
132
+ if (!(dialCode in this.countryCodes)) {
133
+ this.countryCodes[dialCode] = [];
134
+ }
135
+ var index = priority || 0;
136
+ this.countryCodes[dialCode][index] = iso2;
137
+ },
138
+ // filter the given countries using the process function
139
+ _filterCountries: function(countryArray, processFunc) {
140
+ var i;
141
+ // standardise case
142
+ for (i = 0; i < countryArray.length; i++) {
143
+ countryArray[i] = countryArray[i].toLowerCase();
144
+ }
145
+ // build instance country array
146
+ this.countries = [];
147
+ for (i = 0; i < allCountries.length; i++) {
148
+ if (processFunc($.inArray(allCountries[i].iso2, countryArray))) {
149
+ this.countries.push(allCountries[i]);
150
+ }
151
+ }
152
+ },
153
+ // process onlyCountries or excludeCountries array if present
154
+ _processAllCountries: function() {
155
+ if (this.options.onlyCountries.length) {
156
+ // process onlyCountries option
157
+ this._filterCountries(this.options.onlyCountries, function(inArray) {
158
+ // if country is in array
159
+ return inArray != -1;
160
+ });
161
+ } else if (this.options.excludeCountries.length) {
162
+ // process excludeCountries option
163
+ this._filterCountries(this.options.excludeCountries, function(inArray) {
164
+ // if country is not in array
165
+ return inArray == -1;
166
+ });
167
+ } else {
168
+ this.countries = allCountries;
169
+ }
170
+ },
171
+ // process the countryCodes map
172
+ _processCountryCodes: function() {
173
+ this.countryCodes = {};
174
+ for (var i = 0; i < this.countries.length; i++) {
175
+ var c = this.countries[i];
176
+ this._addCountryCode(c.iso2, c.dialCode, c.priority);
177
+ // area codes
178
+ if (c.areaCodes) {
179
+ for (var j = 0; j < c.areaCodes.length; j++) {
180
+ // full dial code is country code + dial code
181
+ this._addCountryCode(c.iso2, c.dialCode + c.areaCodes[j]);
182
+ }
183
+ }
184
+ }
185
+ },
186
+ // process preferred countries - iterate through the preferences, fetching the country data for each one
187
+ _processPreferredCountries: function() {
188
+ this.preferredCountries = [];
189
+ for (var i = 0; i < this.options.preferredCountries.length; i++) {
190
+ var countryCode = this.options.preferredCountries[i].toLowerCase(), countryData = this._getCountryData(countryCode, false, true);
191
+ if (countryData) {
192
+ this.preferredCountries.push(countryData);
193
+ }
194
+ }
195
+ },
196
+ // generate all of the markup for the plugin: the selected flag overlay, and the dropdown
197
+ _generateMarkup: function() {
198
+ // 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)
199
+ this.telInput.attr("autocomplete", "off");
200
+ // containers (mostly for positioning)
201
+ var parentClass = "intl-tel-input";
202
+ if (this.options.allowDropdown) {
203
+ parentClass += " allow-dropdown";
204
+ }
205
+ if (this.options.separateDialCode) {
206
+ parentClass += " separate-dial-code";
207
+ }
208
+ this.telInput.wrap($("<div>", {
209
+ "class": parentClass
210
+ }));
211
+ this.flagsContainer = $("<div>", {
212
+ "class": "flag-container"
213
+ }).insertBefore(this.telInput);
214
+ // currently selected flag (displayed to left of input)
215
+ var selectedFlag = $("<div>", {
216
+ "class": "selected-flag"
217
+ });
218
+ selectedFlag.appendTo(this.flagsContainer);
219
+ this.selectedFlagInner = $("<div>", {
220
+ "class": "iti-flag"
221
+ }).appendTo(selectedFlag);
222
+ if (this.options.separateDialCode) {
223
+ this.selectedDialCode = $("<div>", {
224
+ "class": "selected-dial-code"
225
+ }).appendTo(selectedFlag);
226
+ }
227
+ if (this.options.allowDropdown) {
228
+ // make element focusable and tab naviagable
229
+ selectedFlag.attr("tabindex", "0");
230
+ // CSS triangle
231
+ $("<div>", {
232
+ "class": "iti-arrow"
233
+ }).appendTo(selectedFlag);
234
+ // country dropdown: preferred countries, then divider, then all countries
235
+ this.countryList = $("<ul>", {
236
+ "class": "country-list hide"
237
+ });
238
+ if (this.preferredCountries.length) {
239
+ this._appendListItems(this.preferredCountries, "preferred");
240
+ $("<li>", {
241
+ "class": "divider"
242
+ }).appendTo(this.countryList);
243
+ }
244
+ this._appendListItems(this.countries, "");
245
+ // this is useful in lots of places
246
+ this.countryListItems = this.countryList.children(".country");
247
+ // create dropdownContainer markup
248
+ if (this.options.dropdownContainer) {
249
+ this.dropdown = $("<div>", {
250
+ "class": "intl-tel-input iti-container"
251
+ }).append(this.countryList);
252
+ } else {
253
+ this.countryList.appendTo(this.flagsContainer);
254
+ }
255
+ } else {
256
+ // a little hack so we don't break anything
257
+ this.countryListItems = $();
258
+ }
259
+ },
260
+ // add a country <li> to the countryList <ul> container
261
+ _appendListItems: function(countries, className) {
262
+ // we create so many DOM elements, it is faster to build a temp string
263
+ // and then add everything to the DOM in one go at the end
264
+ var tmp = "";
265
+ // for each country
266
+ for (var i = 0; i < countries.length; i++) {
267
+ var c = countries[i];
268
+ // open the list item
269
+ tmp += "<li class='country " + className + "' data-dial-code='" + c.dialCode + "' data-country-code='" + c.iso2 + "'>";
270
+ // add the flag
271
+ tmp += "<div class='flag-box'><div class='iti-flag " + c.iso2 + "'></div></div>";
272
+ // and the country name and dial code
273
+ tmp += "<span class='country-name'>" + c.name + "</span>";
274
+ tmp += "<span class='dial-code'>+" + c.dialCode + "</span>";
275
+ // close the list item
276
+ tmp += "</li>";
277
+ }
278
+ this.countryList.append(tmp);
279
+ },
280
+ // set the initial state of the input value and the selected flag by:
281
+ // 1. extracting a dial code from the given number
282
+ // 2. using explicit initialCountry
283
+ // 3. picking the first preferred country
284
+ // 4. picking the first country
285
+ _setInitialState: function() {
286
+ var val = this.telInput.val();
287
+ // if we already have a dial code we can go ahead and set the flag, else fall back to default
288
+ if (this._getDialCode(val)) {
289
+ this._updateFlagFromNumber(val, true);
290
+ } else if (this.options.initialCountry !== "auto") {
291
+ // see if we should select a flag
292
+ if (this.options.initialCountry) {
293
+ this._setFlag(this.options.initialCountry, true);
294
+ } else {
295
+ // no dial code and no initialCountry, so default to first in list
296
+ this.defaultCountry = this.preferredCountries.length ? this.preferredCountries[0].iso2 : this.countries[0].iso2;
297
+ if (!val) {
298
+ this._setFlag(this.defaultCountry, true);
299
+ }
300
+ }
301
+ // if empty and no nationalMode and no autoHideDialCode then insert the default dial code
302
+ if (!val && !this.options.nationalMode && !this.options.autoHideDialCode && !this.options.separateDialCode) {
303
+ this.telInput.val("+" + this.selectedCountryData.dialCode);
304
+ }
305
+ }
306
+ // NOTE: if initialCountry is set to auto, that will be handled separately
307
+ // format
308
+ if (val) {
309
+ // this wont be run after _updateDialCode as that's only called if no val
310
+ this._updateValFromNumber(val, this.options.formatOnInit);
311
+ }
312
+ },
313
+ // initialise the main event listeners: input keyup, and click selected flag
314
+ _initListeners: function() {
315
+ this._initKeyListeners();
316
+ if (this.options.autoHideDialCode) {
317
+ this._initFocusListeners();
318
+ }
319
+ if (this.options.allowDropdown) {
320
+ this._initDropdownListeners();
321
+ }
322
+ },
323
+ // initialise the dropdown listeners
324
+ _initDropdownListeners: function() {
325
+ var that = this;
326
+ // 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
327
+ var label = this.telInput.closest("label");
328
+ if (label.length) {
329
+ label.on("click" + this.ns, function(e) {
330
+ // if the dropdown is closed, then focus the input, else ignore the click
331
+ if (that.countryList.hasClass("hide")) {
332
+ that.telInput.focus();
333
+ } else {
334
+ e.preventDefault();
335
+ }
336
+ });
337
+ }
338
+ // toggle country dropdown on click
339
+ var selectedFlag = this.selectedFlagInner.parent();
340
+ selectedFlag.on("click" + this.ns, function(e) {
341
+ // only intercept this event if we're opening the dropdown
342
+ // else let it bubble up to the top ("click-off-to-close" listener)
343
+ // we cannot just stopPropagation as it may be needed to close another instance
344
+ if (that.countryList.hasClass("hide") && !that.telInput.prop("disabled") && !that.telInput.prop("readonly")) {
345
+ that._showDropdown();
346
+ }
347
+ });
348
+ // open dropdown list if currently focused
349
+ this.flagsContainer.on("keydown" + that.ns, function(e) {
350
+ var isDropdownHidden = that.countryList.hasClass("hide");
351
+ if (isDropdownHidden && (e.which == keys.UP || e.which == keys.DOWN || e.which == keys.SPACE || e.which == keys.ENTER)) {
352
+ // prevent form from being submitted if "ENTER" was pressed
353
+ e.preventDefault();
354
+ // prevent event from being handled again by document
355
+ e.stopPropagation();
356
+ that._showDropdown();
357
+ }
358
+ // allow navigation from dropdown to input on TAB
359
+ if (e.which == keys.TAB) {
360
+ that._closeDropdown();
361
+ }
362
+ });
363
+ },
364
+ // init many requests: utils script / geo ip lookup
365
+ _initRequests: function() {
366
+ var that = this;
367
+ // if the user has specified the path to the utils script, fetch it on window.load, else resolve
368
+ if (this.options.utilsScript) {
369
+ // if the plugin is being initialised after the window.load event has already been fired
370
+ if ($.fn[pluginName].windowLoaded) {
371
+ $.fn[pluginName].loadUtils(this.options.utilsScript, this.utilsScriptDeferred);
372
+ } else {
373
+ // wait until the load event so we don't block any other requests e.g. the flags image
374
+ $(window).load(function() {
375
+ $.fn[pluginName].loadUtils(that.options.utilsScript, that.utilsScriptDeferred);
376
+ });
377
+ }
378
+ } else {
379
+ this.utilsScriptDeferred.resolve();
380
+ }
381
+ if (this.options.initialCountry === "auto") {
382
+ this._loadAutoCountry();
383
+ } else {
384
+ this.autoCountryDeferred.resolve();
385
+ }
386
+ },
387
+ // perform the geo ip lookup
388
+ _loadAutoCountry: function() {
389
+ var that = this;
390
+ // check for cookie
391
+ var cookieAutoCountry = window.Cookies ? Cookies.get("itiAutoCountry") : "";
392
+ if (cookieAutoCountry) {
393
+ $.fn[pluginName].autoCountry = cookieAutoCountry;
394
+ }
395
+ // 3 options:
396
+ // 1) already loaded (we're done)
397
+ // 2) not already started loading (start)
398
+ // 3) already started loading (do nothing - just wait for loading callback to fire)
399
+ if ($.fn[pluginName].autoCountry) {
400
+ this.handleAutoCountry();
401
+ } else if (!$.fn[pluginName].startedLoadingAutoCountry) {
402
+ // don't do this twice!
403
+ $.fn[pluginName].startedLoadingAutoCountry = true;
404
+ if (typeof this.options.geoIpLookup === "function") {
405
+ this.options.geoIpLookup(function(countryCode) {
406
+ $.fn[pluginName].autoCountry = countryCode.toLowerCase();
407
+ if (window.Cookies) {
408
+ Cookies.set("itiAutoCountry", $.fn[pluginName].autoCountry, {
409
+ path: "/"
410
+ });
411
+ }
412
+ // tell all instances the auto country is ready
413
+ // TODO: this should just be the current instances
414
+ // 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.
415
+ setTimeout(function() {
416
+ $(".intl-tel-input input").intlTelInput("handleAutoCountry");
417
+ });
418
+ });
419
+ }
420
+ }
421
+ },
422
+ // initialize any key listeners
423
+ _initKeyListeners: function() {
424
+ var that = this;
425
+ // update flag on keyup
426
+ // (keep this listener separate otherwise the setTimeout breaks all the tests)
427
+ this.telInput.on("keyup" + this.ns, function() {
428
+ that._updateFlagFromNumber(that.telInput.val());
429
+ });
430
+ // update flag on cut/paste events (now supported in all major browsers)
431
+ this.telInput.on("cut" + this.ns + " paste" + this.ns + " keyup" + this.ns, function() {
432
+ // hack because "paste" event is fired before input is updated
433
+ setTimeout(function() {
434
+ that._updateFlagFromNumber(that.telInput.val());
435
+ });
436
+ });
437
+ },
438
+ // adhere to the input's maxlength attr
439
+ _cap: function(number) {
440
+ var max = this.telInput.attr("maxlength");
441
+ return max && number.length > max ? number.substr(0, max) : number;
442
+ },
443
+ // listen for mousedown, focus and blur
444
+ _initFocusListeners: function() {
445
+ var that = this;
446
+ // 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
447
+ this.telInput.on("mousedown" + this.ns, function(e) {
448
+ if (!that.telInput.is(":focus") && !that.telInput.val()) {
449
+ e.preventDefault();
450
+ // but this also cancels the focus, so we must trigger that manually
451
+ that.telInput.focus();
452
+ }
453
+ });
454
+ // on focus: if empty, insert the dial code for the currently selected flag
455
+ this.telInput.on("focus" + this.ns, function(e) {
456
+ if (!that.telInput.val() && !that.telInput.prop("readonly") && that.selectedCountryData.dialCode) {
457
+ // insert the dial code
458
+ that.telInput.val("+" + that.selectedCountryData.dialCode);
459
+ // 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
460
+ that.telInput.one("keypress.plus" + that.ns, function(e) {
461
+ if (e.which == keys.PLUS) {
462
+ that.telInput.val("");
463
+ }
464
+ });
465
+ // 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
466
+ setTimeout(function() {
467
+ var input = that.telInput[0];
468
+ if (that.isGoodBrowser) {
469
+ var len = that.telInput.val().length;
470
+ input.setSelectionRange(len, len);
471
+ }
472
+ });
473
+ }
474
+ });
475
+ // on blur or form submit: if just a dial code then remove it
476
+ var form = this.telInput.prop("form");
477
+ if (form) {
478
+ $(form).on("submit" + this.ns, function() {
479
+ that._removeEmptyDialCode();
480
+ });
481
+ }
482
+ this.telInput.on("blur" + this.ns, function() {
483
+ that._removeEmptyDialCode();
484
+ });
485
+ },
486
+ _removeEmptyDialCode: function() {
487
+ var value = this.telInput.val(), startsPlus = value.charAt(0) == "+";
488
+ if (startsPlus) {
489
+ var numeric = this._getNumeric(value);
490
+ // if just a plus, or if just a dial code
491
+ if (!numeric || this.selectedCountryData.dialCode == numeric) {
492
+ this.telInput.val("");
493
+ }
494
+ }
495
+ // remove the keypress listener we added on focus
496
+ this.telInput.off("keypress.plus" + this.ns);
497
+ },
498
+ // extract the numeric digits from the given string
499
+ _getNumeric: function(s) {
500
+ return s.replace(/\D/g, "");
501
+ },
502
+ // show the dropdown
503
+ _showDropdown: function() {
504
+ this._setDropdownPosition();
505
+ // update highlighting and scroll to active list item
506
+ var activeListItem = this.countryList.children(".active");
507
+ if (activeListItem.length) {
508
+ this._highlightListItem(activeListItem);
509
+ this._scrollTo(activeListItem);
510
+ }
511
+ // bind all the dropdown-related listeners: mouseover, click, click-off, keydown
512
+ this._bindDropdownListeners();
513
+ // update the arrow
514
+ this.selectedFlagInner.children(".iti-arrow").addClass("up");
515
+ },
516
+ // decide where to position dropdown (depends on position within viewport, and scroll)
517
+ _setDropdownPosition: function() {
518
+ var that = this;
519
+ if (this.options.dropdownContainer) {
520
+ this.dropdown.appendTo(this.options.dropdownContainer);
521
+ }
522
+ // show the menu and grab the dropdown height
523
+ this.dropdownHeight = this.countryList.removeClass("hide").outerHeight();
524
+ if (!this.isMobile) {
525
+ var pos = this.telInput.offset(), inputTop = pos.top, windowTop = $(window).scrollTop(), // dropdownFitsBelow = (dropdownBottom < windowBottom)
526
+ dropdownFitsBelow = inputTop + this.telInput.outerHeight() + this.dropdownHeight < windowTop + $(window).height(), dropdownFitsAbove = inputTop - this.dropdownHeight > windowTop;
527
+ // by default, the dropdown will be below the input. If we want to position it above the input, we add the dropup class.
528
+ this.countryList.toggleClass("dropup", !dropdownFitsBelow && dropdownFitsAbove);
529
+ // if dropdownContainer is enabled, calculate postion
530
+ if (this.options.dropdownContainer) {
531
+ // 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.
532
+ var extraTop = !dropdownFitsBelow && dropdownFitsAbove ? 0 : this.telInput.innerHeight();
533
+ // calculate placement
534
+ this.dropdown.css({
535
+ top: inputTop + extraTop,
536
+ left: pos.left
537
+ });
538
+ // close menu on window scroll
539
+ $(window).on("scroll" + this.ns, function() {
540
+ that._closeDropdown();
541
+ });
542
+ }
543
+ }
544
+ },
545
+ // we only bind dropdown listeners when the dropdown is open
546
+ _bindDropdownListeners: function() {
547
+ var that = this;
548
+ // when mouse over a list item, just highlight that one
549
+ // we add the class "highlight", so if they hit "enter" we know which one to select
550
+ this.countryList.on("mouseover" + this.ns, ".country", function(e) {
551
+ that._highlightListItem($(this));
552
+ });
553
+ // listen for country selection
554
+ this.countryList.on("click" + this.ns, ".country", function(e) {
555
+ that._selectListItem($(this));
556
+ });
557
+ // click off to close
558
+ // (except when this initial opening click is bubbling up)
559
+ // we cannot just stopPropagation as it may be needed to close another instance
560
+ var isOpening = true;
561
+ $("html").on("click" + this.ns, function(e) {
562
+ if (!isOpening) {
563
+ that._closeDropdown();
564
+ }
565
+ isOpening = false;
566
+ });
567
+ // listen for up/down scrolling, enter to select, or letters to jump to country name.
568
+ // use keydown as keypress doesn't fire for non-char keys and we want to catch if they
569
+ // just hit down and hold it to scroll down (no keyup event).
570
+ // listen on the document because that's where key events are triggered if no input has focus
571
+ var query = "", queryTimer = null;
572
+ $(document).on("keydown" + this.ns, function(e) {
573
+ // prevent down key from scrolling the whole page,
574
+ // and enter key from submitting a form etc
575
+ e.preventDefault();
576
+ if (e.which == keys.UP || e.which == keys.DOWN) {
577
+ // up and down to navigate
578
+ that._handleUpDownKey(e.which);
579
+ } else if (e.which == keys.ENTER) {
580
+ // enter to select
581
+ that._handleEnterKey();
582
+ } else if (e.which == keys.ESC) {
583
+ // esc to close
584
+ that._closeDropdown();
585
+ } else if (e.which >= keys.A && e.which <= keys.Z || e.which == keys.SPACE) {
586
+ // upper case letters (note: keyup/keydown only return upper case letters)
587
+ // jump to countries that start with the query string
588
+ if (queryTimer) {
589
+ clearTimeout(queryTimer);
590
+ }
591
+ query += String.fromCharCode(e.which);
592
+ that._searchForCountry(query);
593
+ // if the timer hits 1 second, reset the query
594
+ queryTimer = setTimeout(function() {
595
+ query = "";
596
+ }, 1e3);
597
+ }
598
+ });
599
+ },
600
+ // highlight the next/prev item in the list (and ensure it is visible)
601
+ _handleUpDownKey: function(key) {
602
+ var current = this.countryList.children(".highlight").first();
603
+ var next = key == keys.UP ? current.prev() : current.next();
604
+ if (next.length) {
605
+ // skip the divider
606
+ if (next.hasClass("divider")) {
607
+ next = key == keys.UP ? next.prev() : next.next();
608
+ }
609
+ this._highlightListItem(next);
610
+ this._scrollTo(next);
611
+ }
612
+ },
613
+ // select the currently highlighted item
614
+ _handleEnterKey: function() {
615
+ var currentCountry = this.countryList.children(".highlight").first();
616
+ if (currentCountry.length) {
617
+ this._selectListItem(currentCountry);
618
+ }
619
+ },
620
+ // find the first list item whose name starts with the query string
621
+ _searchForCountry: function(query) {
622
+ for (var i = 0; i < this.countries.length; i++) {
623
+ if (this._startsWith(this.countries[i].name, query)) {
624
+ var listItem = this.countryList.children("[data-country-code=" + this.countries[i].iso2 + "]").not(".preferred");
625
+ // update highlighting and scroll
626
+ this._highlightListItem(listItem);
627
+ this._scrollTo(listItem, true);
628
+ break;
629
+ }
630
+ }
631
+ },
632
+ // check if (uppercase) string a starts with string b
633
+ _startsWith: function(a, b) {
634
+ return a.substr(0, b.length).toUpperCase() == b;
635
+ },
636
+ // update the input's value to the given val (format first if possible)
637
+ // NOTE: this is called from _setInitialState, handleUtils and setNumber
638
+ _updateValFromNumber: function(number, doFormat) {
639
+ if (doFormat && window.intlTelInputUtils && this.selectedCountryData) {
640
+ var format = !this.options.separateDialCode && (this.options.nationalMode || number.charAt(0) != "+") ? intlTelInputUtils.numberFormat.NATIONAL : intlTelInputUtils.numberFormat.INTERNATIONAL;
641
+ number = intlTelInputUtils.formatNumber(number, this.selectedCountryData.iso2, format);
642
+ }
643
+ number = this._beforeSetNumber(number);
644
+ this.telInput.val(number);
645
+ },
646
+ // check if need to select a new flag based on the given number
647
+ // Note: called from _setInitialState, keyup handler, setNumber
648
+ _updateFlagFromNumber: function(number, isInit) {
649
+ // 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
650
+ // 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
651
+ if (number && this.options.nationalMode && this.selectedCountryData && this.selectedCountryData.dialCode == "1" && number.charAt(0) != "+") {
652
+ if (number.charAt(0) != "1") {
653
+ number = "1" + number;
654
+ }
655
+ number = "+" + number;
656
+ }
657
+ // try and extract valid dial code from input
658
+ var dialCode = this._getDialCode(number), countryCode = null;
659
+ if (dialCode) {
660
+ // check if one of the matching countries is already selected
661
+ var countryCodes = this.countryCodes[this._getNumeric(dialCode)], alreadySelected = this.selectedCountryData && $.inArray(this.selectedCountryData.iso2, countryCodes) != -1;
662
+ // if a matching country is not already selected (or this is an unknown NANP area code): choose the first in the list
663
+ if (!alreadySelected || this._isUnknownNanp(number, dialCode)) {
664
+ // if using onlyCountries option, countryCodes[0] may be empty, so we must find the first non-empty index
665
+ for (var j = 0; j < countryCodes.length; j++) {
666
+ if (countryCodes[j]) {
667
+ countryCode = countryCodes[j];
668
+ break;
669
+ }
670
+ }
671
+ }
672
+ } else if (number.charAt(0) == "+" && this._getNumeric(number).length) {
673
+ // invalid dial code, so empty
674
+ // Note: use getNumeric here because the number has not been formatted yet, so could contain bad chars
675
+ countryCode = "";
676
+ } else if (!number || number == "+") {
677
+ // empty, or just a plus, so default
678
+ countryCode = this.defaultCountry;
679
+ }
680
+ if (countryCode !== null) {
681
+ this._setFlag(countryCode, isInit);
682
+ }
683
+ },
684
+ // 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 (instead of say +1 702) and the actual number's length is >=4
685
+ _isUnknownNanp: function(number, dialCode) {
686
+ return dialCode == "+1" && this._getNumeric(number).length >= 4;
687
+ },
688
+ // remove highlighting from other list items and highlight the given item
689
+ _highlightListItem: function(listItem) {
690
+ this.countryListItems.removeClass("highlight");
691
+ listItem.addClass("highlight");
692
+ },
693
+ // find the country data for the given country code
694
+ // the ignoreOnlyCountriesOption is only used during init() while parsing the onlyCountries array
695
+ _getCountryData: function(countryCode, ignoreOnlyCountriesOption, allowFail) {
696
+ var countryList = ignoreOnlyCountriesOption ? allCountries : this.countries;
697
+ for (var i = 0; i < countryList.length; i++) {
698
+ if (countryList[i].iso2 == countryCode) {
699
+ return countryList[i];
700
+ }
701
+ }
702
+ if (allowFail) {
703
+ return null;
704
+ } else {
705
+ throw new Error("No country data for '" + countryCode + "'");
706
+ }
707
+ },
708
+ // select the given flag, update the placeholder and the active list item
709
+ // Note: called from _setInitialState, _updateFlagFromNumber, _selectListItem, setCountry
710
+ _setFlag: function(countryCode, isInit) {
711
+ var prevCountry = this.selectedCountryData && this.selectedCountryData.iso2 ? this.selectedCountryData : {};
712
+ // do this first as it will throw an error and stop if countryCode is invalid
713
+ this.selectedCountryData = countryCode ? this._getCountryData(countryCode, false, false) : {};
714
+ // update the defaultCountry - we only need the iso2 from now on, so just store that
715
+ if (this.selectedCountryData.iso2) {
716
+ this.defaultCountry = this.selectedCountryData.iso2;
717
+ }
718
+ this.selectedFlagInner.attr("class", "iti-flag " + countryCode);
719
+ // update the selected country's title attribute
720
+ var title = countryCode ? this.selectedCountryData.name + ": +" + this.selectedCountryData.dialCode : "Unknown";
721
+ this.selectedFlagInner.parent().attr("title", title);
722
+ if (this.options.separateDialCode) {
723
+ var dialCode = this.selectedCountryData.dialCode ? "+" + this.selectedCountryData.dialCode : "", parent = this.telInput.parent();
724
+ if (prevCountry.dialCode) {
725
+ parent.removeClass("iti-sdc-" + (prevCountry.dialCode.length + 1));
726
+ }
727
+ if (dialCode) {
728
+ parent.addClass("iti-sdc-" + dialCode.length);
729
+ }
730
+ this.selectedDialCode.text(dialCode);
731
+ }
732
+ // and the input's placeholder
733
+ this._updatePlaceholder();
734
+ // update the active list item
735
+ this.countryListItems.removeClass("active");
736
+ if (countryCode) {
737
+ this.countryListItems.find(".iti-flag." + countryCode).first().closest(".country").addClass("active");
738
+ }
739
+ // on change flag, trigger a custom event
740
+ if (!isInit && prevCountry.iso2 !== countryCode) {
741
+ this.telInput.trigger("countrychange", this.selectedCountryData);
742
+ }
743
+ },
744
+ // update the input placeholder to an example number from the currently selected country
745
+ _updatePlaceholder: function() {
746
+ if (window.intlTelInputUtils && !this.hadInitialPlaceholder && this.options.autoPlaceholder && this.selectedCountryData) {
747
+ var numberType = intlTelInputUtils.numberType[this.options.numberType], placeholder = this.selectedCountryData.iso2 ? intlTelInputUtils.getExampleNumber(this.selectedCountryData.iso2, this.options.nationalMode, numberType) : "";
748
+ placeholder = this._beforeSetNumber(placeholder);
749
+ if (typeof this.options.customPlaceholder === "function") {
750
+ placeholder = this.options.customPlaceholder(placeholder, this.selectedCountryData);
751
+ }
752
+ this.telInput.attr("placeholder", placeholder);
753
+ }
754
+ },
755
+ // called when the user selects a list item from the dropdown
756
+ _selectListItem: function(listItem) {
757
+ // update selected flag and active list item
758
+ this._setFlag(listItem.attr("data-country-code"));
759
+ this._closeDropdown();
760
+ this._updateDialCode(listItem.attr("data-dial-code"), true);
761
+ // focus the input
762
+ this.telInput.focus();
763
+ // 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
764
+ if (this.isGoodBrowser) {
765
+ var len = this.telInput.val().length;
766
+ this.telInput[0].setSelectionRange(len, len);
767
+ }
768
+ },
769
+ // close the dropdown and unbind any listeners
770
+ _closeDropdown: function() {
771
+ this.countryList.addClass("hide");
772
+ // update the arrow
773
+ this.selectedFlagInner.children(".iti-arrow").removeClass("up");
774
+ // unbind key events
775
+ $(document).off(this.ns);
776
+ // unbind click-off-to-close
777
+ $("html").off(this.ns);
778
+ // unbind hover and click listeners
779
+ this.countryList.off(this.ns);
780
+ // remove menu from container
781
+ if (this.options.dropdownContainer) {
782
+ if (!this.isMobile) {
783
+ $(window).off("scroll" + this.ns);
784
+ }
785
+ this.dropdown.detach();
786
+ }
787
+ },
788
+ // check if an element is visible within it's container, else scroll until it is
789
+ _scrollTo: function(element, middle) {
790
+ 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;
791
+ if (elementTop < containerTop) {
792
+ // scroll up
793
+ if (middle) {
794
+ newScrollTop -= middleOffset;
795
+ }
796
+ container.scrollTop(newScrollTop);
797
+ } else if (elementBottom > containerBottom) {
798
+ // scroll down
799
+ if (middle) {
800
+ newScrollTop += middleOffset;
801
+ }
802
+ var heightDifference = containerHeight - elementHeight;
803
+ container.scrollTop(newScrollTop - heightDifference);
804
+ }
805
+ },
806
+ // replace any existing dial code with the new one
807
+ // Note: called from _selectListItem and setCountry
808
+ _updateDialCode: function(newDialCode, hasSelectedListItem) {
809
+ var inputVal = this.telInput.val(), newNumber;
810
+ // save having to pass this every time
811
+ newDialCode = "+" + newDialCode;
812
+ if (inputVal.charAt(0) == "+") {
813
+ // there's a plus so we're dealing with a replacement (doesn't matter if nationalMode or not)
814
+ var prevDialCode = this._getDialCode(inputVal);
815
+ if (prevDialCode) {
816
+ // current number contains a valid dial code, so replace it
817
+ newNumber = inputVal.replace(prevDialCode, newDialCode);
818
+ } else {
819
+ // current number contains an invalid dial code, so ditch it
820
+ // (no way to determine where the invalid dial code ends and the rest of the number begins)
821
+ newNumber = newDialCode;
822
+ }
823
+ } else if (this.options.nationalMode || this.options.separateDialCode) {
824
+ // don't do anything
825
+ return;
826
+ } else {
827
+ // nationalMode is disabled
828
+ if (inputVal) {
829
+ // there is an existing value with no dial code: prefix the new dial code
830
+ newNumber = newDialCode + inputVal;
831
+ } else if (hasSelectedListItem || !this.options.autoHideDialCode) {
832
+ // no existing value and either they've just selected a list item, or autoHideDialCode is disabled: insert new dial code
833
+ newNumber = newDialCode;
834
+ } else {
835
+ return;
836
+ }
837
+ }
838
+ this.telInput.val(newNumber);
839
+ },
840
+ // try and extract a valid international dial code from a full telephone number
841
+ // Note: returns the raw string inc plus character and any whitespace/dots etc
842
+ _getDialCode: function(number) {
843
+ var dialCode = "";
844
+ // only interested in international numbers (starting with a plus)
845
+ if (number.charAt(0) == "+") {
846
+ var numericChars = "";
847
+ // iterate over chars
848
+ for (var i = 0; i < number.length; i++) {
849
+ var c = number.charAt(i);
850
+ // if char is number
851
+ if ($.isNumeric(c)) {
852
+ numericChars += c;
853
+ // if current numericChars make a valid dial code
854
+ if (this.countryCodes[numericChars]) {
855
+ // store the actual raw string (useful for matching later)
856
+ dialCode = number.substr(0, i + 1);
857
+ }
858
+ // longest dial code is 4 chars
859
+ if (numericChars.length == 4) {
860
+ break;
861
+ }
862
+ }
863
+ }
864
+ }
865
+ return dialCode;
866
+ },
867
+ // get the input val, adding the dial code if separateDialCode is enabled
868
+ _getFullNumber: function() {
869
+ var prefix = this.options.separateDialCode ? "+" + this.selectedCountryData.dialCode : "";
870
+ return prefix + this.telInput.val();
871
+ },
872
+ // remove the dial code if separateDialCode is enabled
873
+ _beforeSetNumber: function(number) {
874
+ if (this.options.separateDialCode) {
875
+ var dialCode = this._getDialCode(number);
876
+ if (dialCode) {
877
+ // US dialCode is "+1", which is what we want
878
+ // CA dialCode is "+1 123", which is wrong - should be "+1" (as it has multiple area codes)
879
+ // AS dialCode is "+1 684", which is what we want
880
+ // Solution: if the country has area codes, then revert to just the dial code
881
+ if (this.selectedCountryData.areaCodes !== null) {
882
+ dialCode = "+" + this.selectedCountryData.dialCode;
883
+ }
884
+ // 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
885
+ // NOTE: don't just trim all non-numerics as may want to preserve an open parenthesis etc
886
+ var start = number[dialCode.length] === " " || number[dialCode.length] === "-" ? dialCode.length + 1 : dialCode.length;
887
+ number = number.substr(start);
888
+ }
889
+ }
890
+ return this._cap(number);
891
+ },
892
+ /********************
893
+ * PUBLIC METHODS
894
+ ********************/
895
+ // this is called when the geoip call returns
896
+ handleAutoCountry: function() {
897
+ if (this.options.initialCountry === "auto") {
898
+ // 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
899
+ this.defaultCountry = $.fn[pluginName].autoCountry;
900
+ // if there's no initial value in the input, then update the flag
901
+ if (!this.telInput.val()) {
902
+ this.setCountry(this.defaultCountry);
903
+ }
904
+ this.autoCountryDeferred.resolve();
905
+ }
906
+ },
907
+ // remove plugin
908
+ destroy: function() {
909
+ if (this.allowDropdown) {
910
+ // make sure the dropdown is closed (and unbind listeners)
911
+ this._closeDropdown();
912
+ // click event to open dropdown
913
+ this.selectedFlagInner.parent().off(this.ns);
914
+ // label click hack
915
+ this.telInput.closest("label").off(this.ns);
916
+ }
917
+ // unbind submit event handler on form
918
+ if (this.options.autoHideDialCode) {
919
+ var form = this.telInput.prop("form");
920
+ if (form) {
921
+ $(form).off(this.ns);
922
+ }
923
+ }
924
+ // unbind all events: key events, and focus/blur events if autoHideDialCode=true
925
+ this.telInput.off(this.ns);
926
+ // remove markup (but leave the original input)
927
+ var container = this.telInput.parent();
928
+ container.before(this.telInput).remove();
929
+ },
930
+ // get the extension from the current number
931
+ getExtension: function() {
932
+ if (window.intlTelInputUtils) {
933
+ return intlTelInputUtils.getExtension(this._getFullNumber(), this.selectedCountryData.iso2);
934
+ }
935
+ return "";
936
+ },
937
+ // format the number to the given format
938
+ getNumber: function(format) {
939
+ if (window.intlTelInputUtils) {
940
+ return intlTelInputUtils.formatNumber(this._getFullNumber(), this.selectedCountryData.iso2, format);
941
+ }
942
+ return "";
943
+ },
944
+ // get the type of the entered number e.g. landline/mobile
945
+ getNumberType: function() {
946
+ if (window.intlTelInputUtils) {
947
+ return intlTelInputUtils.getNumberType(this._getFullNumber(), this.selectedCountryData.iso2);
948
+ }
949
+ return -99;
950
+ },
951
+ // get the country data for the currently selected flag
952
+ getSelectedCountryData: function() {
953
+ // if this is undefined, the plugin will return it's instance instead, so in that case an empty object makes more sense
954
+ return this.selectedCountryData || {};
955
+ },
956
+ // get the validation error
957
+ getValidationError: function() {
958
+ if (window.intlTelInputUtils) {
959
+ return intlTelInputUtils.getValidationError(this._getFullNumber(), this.selectedCountryData.iso2);
960
+ }
961
+ return -99;
962
+ },
963
+ // validate the input val - assumes the global function isValidNumber (from utilsScript)
964
+ isValidNumber: function() {
965
+ var val = $.trim(this._getFullNumber()), countryCode = this.options.nationalMode ? this.selectedCountryData.iso2 : "";
966
+ return window.intlTelInputUtils ? intlTelInputUtils.isValidNumber(val, countryCode) : null;
967
+ },
968
+ // update the selected flag, and update the input val accordingly
969
+ setCountry: function(countryCode) {
970
+ countryCode = countryCode.toLowerCase();
971
+ // check if already selected
972
+ if (!this.selectedFlagInner.hasClass(countryCode)) {
973
+ this._setFlag(countryCode);
974
+ this._updateDialCode(this.selectedCountryData.dialCode, false);
975
+ }
976
+ },
977
+ // set the input value and update the flag
978
+ // NOTE: preventFormat arg is for public method
979
+ setNumber: function(number, preventFormat) {
980
+ // we must update the flag first, which updates this.selectedCountryData, which is used for formatting the number before displaying it
981
+ this._updateFlagFromNumber(number);
982
+ this._updateValFromNumber(number, !preventFormat);
983
+ },
984
+ // this is called when the utils request completes
985
+ handleUtils: function() {
986
+ // if the request was successful
987
+ if (window.intlTelInputUtils) {
988
+ // if there's an initial value in the input, then format it
989
+ if (this.telInput.val()) {
990
+ this._updateValFromNumber(this.telInput.val(), this.options.formatOnInit);
991
+ }
992
+ this._updatePlaceholder();
993
+ }
994
+ this.utilsScriptDeferred.resolve();
995
+ }
996
+ };
997
+ // using https://github.com/jquery-boilerplate/jquery-boilerplate/wiki/Extending-jQuery-Boilerplate
998
+ // (adapted to allow public functions)
999
+ $.fn[pluginName] = function(options) {
1000
+ var args = arguments;
1001
+ // Is the first parameter an object (options), or was omitted,
1002
+ // instantiate a new instance of the plugin.
1003
+ if (options === undefined || typeof options === "object") {
1004
+ // collect all of the deferred objects for all instances created with this selector
1005
+ var deferreds = [];
1006
+ this.each(function() {
1007
+ if (!$.data(this, "plugin_" + pluginName)) {
1008
+ var instance = new Plugin(this, options);
1009
+ var instanceDeferreds = instance._init();
1010
+ // we now have 2 deffereds: 1 for auto country, 1 for utils script
1011
+ deferreds.push(instanceDeferreds[0]);
1012
+ deferreds.push(instanceDeferreds[1]);
1013
+ $.data(this, "plugin_" + pluginName, instance);
1014
+ }
1015
+ });
1016
+ // return the promise from the "master" deferred object that tracks all the others
1017
+ return $.when.apply(null, deferreds);
1018
+ } else if (typeof options === "string" && options[0] !== "_") {
1019
+ // If the first parameter is a string and it doesn't start
1020
+ // with an underscore or "contains" the `init`-function,
1021
+ // treat this as a call to a public method.
1022
+ // Cache the method call to make it possible to return a value
1023
+ var returns;
1024
+ this.each(function() {
1025
+ var instance = $.data(this, "plugin_" + pluginName);
1026
+ // Tests that there's already a plugin-instance
1027
+ // and checks that the requested public method exists
1028
+ if (instance instanceof Plugin && typeof instance[options] === "function") {
1029
+ // Call the method of our plugin instance,
1030
+ // and pass it the supplied arguments.
1031
+ returns = instance[options].apply(instance, Array.prototype.slice.call(args, 1));
1032
+ }
1033
+ // Allow instances to be destroyed via the 'destroy' method
1034
+ if (options === "destroy") {
1035
+ $.data(this, "plugin_" + pluginName, null);
1036
+ }
1037
+ });
1038
+ // If the earlier cached method gives a value back return the value,
1039
+ // otherwise return this to preserve chainability.
1040
+ return returns !== undefined ? returns : this;
1041
+ }
1042
+ };
1043
+ /********************
1044
+ * STATIC METHODS
1045
+ ********************/
1046
+ // get the country data object
1047
+ $.fn[pluginName].getCountryData = function() {
1048
+ return allCountries;
1049
+ };
1050
+ // load the utils script
1051
+ $.fn[pluginName].loadUtils = function(path, utilsScriptDeferred) {
1052
+ if (!$.fn[pluginName].loadedUtilsScript) {
1053
+ // 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)
1054
+ $.fn[pluginName].loadedUtilsScript = true;
1055
+ // dont use $.getScript as it prevents caching
1056
+ $.ajax({
1057
+ url: path,
1058
+ complete: function() {
1059
+ // tell all instances that the utils request is complete
1060
+ $(".intl-tel-input input").intlTelInput("handleUtils");
1061
+ },
1062
+ dataType: "script",
1063
+ cache: true
1064
+ });
1065
+ } else if (utilsScriptDeferred) {
1066
+ utilsScriptDeferred.resolve();
1067
+ }
1068
+ };
1069
+ // version
1070
+ $.fn[pluginName].version = "8.5.2";
1071
+ // Tell JSHint to ignore this warning: "character may get silently deleted by one or more browsers"
1072
+ // jshint -W100
1073
+ // Array of country objects for the flag dropdown.
1074
+ // Each contains a name, country code (ISO 3166-1 alpha-2) and dial code.
1075
+ // Originally from https://github.com/mledoze/countries
1076
+ // then with a couple of manual re-arrangements to be alphabetical
1077
+ // then changed Kazakhstan from +76 to +7
1078
+ // and Vatican City from +379 to +39 (see issue 50)
1079
+ // and Caribean Netherlands from +5997 to +599
1080
+ // and Curacao from +5999 to +599
1081
+ // Removed: Kosovo, Pitcairn Islands, South Georgia
1082
+ // UPDATE Sept 12th 2015
1083
+ // List of regions that have iso2 country codes, which I have chosen to omit:
1084
+ // (based on this information: https://en.wikipedia.org/wiki/List_of_country_calling_codes)
1085
+ // AQ - Antarctica - all different country codes depending on which "base"
1086
+ // BV - Bouvet Island - no calling code
1087
+ // GS - South Georgia and the South Sandwich Islands - "inhospitable collection of islands" - same flag and calling code as Falkland Islands
1088
+ // HM - Heard Island and McDonald Islands - no calling code
1089
+ // PN - Pitcairn - tiny population (56), same calling code as New Zealand
1090
+ // TF - French Southern Territories - no calling code
1091
+ // UM - United States Minor Outlying Islands - no calling code
1092
+ // UPDATE the criteria of supported countries or territories (see issue 297)
1093
+ // Have an iso2 code: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
1094
+ // Have a country calling code: https://en.wikipedia.org/wiki/List_of_country_calling_codes
1095
+ // Have a flag
1096
+ // Must be supported by libphonenumber: https://github.com/googlei18n/libphonenumber
1097
+ // Update: converted objects to arrays to save bytes!
1098
+ // Update: added "priority" for countries with the same dialCode as others
1099
+ // Update: added array of area codes for countries with the same dialCode as others
1100
+ // So each country array has the following information:
1101
+ // [
1102
+ // Country name,
1103
+ // iso2 code,
1104
+ // International dial code,
1105
+ // Order (if >1 country with same dial code),
1106
+ // Area codes (if >1 country with same dial code)
1107
+ // ]
1108
+ 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" ], [ "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 ] ];
1109
+ // loop over all of the countries above
1110
+ for (var i = 0; i < allCountries.length; i++) {
1111
+ var c = allCountries[i];
1112
+ allCountries[i] = {
1113
+ name: c[0],
1114
+ iso2: c[1],
1115
+ dialCode: c[2],
1116
+ priority: c[3] || 0,
1117
+ areaCodes: c[4] || null
1118
+ };
1119
+ }
1120
+ });