intl-tel-input-rails 4.0.0.1 → 6.0.4

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: a9bca9a8c8788e3279ab8863b0a7cd644b2f80ec
4
- data.tar.gz: 7a63f370ebcc7c98ea2592136b55236cadf5060d
3
+ metadata.gz: c8255866e41e737afe59cc31c0757abcd5a74f8e
4
+ data.tar.gz: ecbbeb3c887fb60d3e515534c695d138efe440ee
5
5
  SHA512:
6
- metadata.gz: 0aaf7827a65aeeb1ea0e244eb3a68ca1d3f4d4ddb8112eaa8e60c3f6158be8bf258f800af3c968b8129f30898e2b93fc1aeb5cb05948abafad51eb5d3cb921fe
7
- data.tar.gz: c4454234dc823a4188af830174dfbfdb6aa7f645c020c15b938ca757c4b1d773bc96b4dfe1d982f348d5b3a9aa57c91d066d750616f0c64e1b379dbb8769fa2c
6
+ metadata.gz: 77fa682d735fd6edc8a54878bbfd21a8450f4e5e8cc97b481c3e3cd22fca150121c1f3b40af3cd3908db4ec9fdcbbebbaa7225091a0c4f306bc7fa467b0dad56
7
+ data.tar.gz: 337d788124aa11cd6a7b88393b88b7f7e36ed34309b8dfaf1be5db8db07d04090a79d186e6baa8ca4994d10ac2dafd5d9861876f5f8d531569c4af0eeffe3e65
@@ -1,4 +1,4 @@
1
- Copyright (c) 2014 Ilias Spyropoulos
1
+ Copyright (c) 2014, 2015 Ilias Spyropoulos
2
2
 
3
3
  MIT License
4
4
 
data/README.md CHANGED
@@ -3,6 +3,8 @@
3
3
  This gem is a simple wrapper for the [intl-tel-input](https://github.com/Bluefieldscom/intl-tel-input)
4
4
  library.
5
5
 
6
+ [![Gem Version](https://badge.fury.io/rb/intl-tel-input-rails@2x.png)](http://badge.fury.io/rb/intl-tel-input-rails)
7
+
6
8
  ## Installation
7
9
 
8
10
  Add this line to your application's Gemfile:
@@ -33,4 +35,4 @@ Add the following directive to your Stylesheet manifest file:
33
35
 
34
36
  ## Versioning
35
37
 
36
- intl-tel-input-rails 4.0.0.1 == intl-tel-input 4.0.0
38
+ intl-tel-input-rails 6.0.4 == intl-tel-input 6.0.4
@@ -10,7 +10,7 @@ Gem::Specification.new do |spec|
10
10
  spec.summary = %q{intl-tel-input for the Rails asset pipeline.}
11
11
  spec.description = <<-EOF
12
12
  A jQuery plugin for entering and validating international telephone numbers.
13
- This gem allows for its easy inclusion into the rails asset pipeline.
13
+ This gem allows for its easy inclusion into the Rails asset pipeline.
14
14
  EOF
15
15
  spec.homepage = "https://github.com/ispyropoulos/intl-tel-input-rails"
16
16
  spec.license = "MIT"
@@ -1,3 +1,3 @@
1
1
  module IntlTelInput
2
- VERSION = '4.0.0.1'
2
+ VERSION = '6.0.4'
3
3
  end
@@ -1,5 +1,5 @@
1
1
  /*
2
- International Telephone Input v4.0.0
2
+ International Telephone Input v6.0.4
3
3
  https://github.com/Bluefieldscom/intl-tel-input.git
4
4
  */
5
5
  // wrap in UMD - see https://github.com/umdjs/umd/blob/master/jqueryPlugin.js
@@ -13,16 +13,21 @@ https://github.com/Bluefieldscom/intl-tel-input.git
13
13
  }
14
14
  })(function($, window, document, undefined) {
15
15
  "use strict";
16
+ // these vars persist through all instances of the plugin
16
17
  var pluginName = "intlTelInput", id = 1, // give each instance it's own id for namespaced event handling
17
18
  defaults = {
19
+ // typing digits after a valid number will be added to the extension part of the number
20
+ allowExtensions: false,
18
21
  // automatically format the number according to the selected country
19
22
  autoFormat: true,
20
23
  // if there is just a dial code in the input: remove it on blur, and re-add it on focus
21
24
  autoHideDialCode: true,
25
+ // add or remove input placeholder with an example number for the selected country
26
+ autoPlaceholder: true,
22
27
  // default country
23
28
  defaultCountry: "",
24
- // token for ipinfo - required for https or over 1000 daily page views support
25
- ipinfoToken: "",
29
+ // geoIp lookup function
30
+ geoIpLookup: null,
26
31
  // don't insert international dial codes
27
32
  nationalMode: true,
28
33
  // number type to use for placeholders
@@ -31,8 +36,6 @@ https://github.com/Bluefieldscom/intl-tel-input.git
31
36
  onlyCountries: [],
32
37
  // the countries at the top of the list. defaults to united states and united kingdom
33
38
  preferredCountries: [ "us", "gb" ],
34
- // stop the user from typing invalid numbers
35
- preventInvalidNumbers: false,
36
39
  // specify the path to the libphonenumber script to enable validation/formatting
37
40
  utilsScript: ""
38
41
  }, keys = {
@@ -47,6 +50,7 @@ https://github.com/Bluefieldscom/intl-tel-input.git
47
50
  NINE: 57,
48
51
  SPACE: 32,
49
52
  BSPACE: 8,
53
+ TAB: 9,
50
54
  DEL: 46,
51
55
  CTRL: 17,
52
56
  CMD1: 91,
@@ -67,31 +71,9 @@ https://github.com/Bluefieldscom/intl-tel-input.git
67
71
  this.isGoodBrowser = Boolean(element.setSelectionRange);
68
72
  this.hadInitialPlaceholder = Boolean($(element).attr("placeholder"));
69
73
  this._name = pluginName;
70
- this.init();
71
74
  }
72
75
  Plugin.prototype = {
73
- init: function() {
74
- var that = this;
75
- // if defaultCountry is set to "auto", we must do a lookup first
76
- if (this.options.defaultCountry == "auto") {
77
- // reset this in case lookup fails
78
- this.options.defaultCountry = "";
79
- var ipinfoURL = "//ipinfo.io";
80
- if (this.options.ipinfoToken) {
81
- ipinfoURL += "?token=" + this.options.ipinfoToken;
82
- }
83
- $.get(ipinfoURL, function(response) {
84
- if (response && response.country) {
85
- that.options.defaultCountry = response.country.toLowerCase();
86
- }
87
- }, "jsonp").always(function() {
88
- that._ready();
89
- });
90
- } else {
91
- this._ready();
92
- }
93
- },
94
- _ready: function() {
76
+ _init: function() {
95
77
  // if in nationalMode, disable options relating to dial codes
96
78
  if (this.options.nationalMode) {
97
79
  this.options.autoHideDialCode = false;
@@ -100,6 +82,14 @@ https://github.com/Bluefieldscom/intl-tel-input.git
100
82
  if (navigator.userAgent.match(/IEMobile/i)) {
101
83
  this.options.autoFormat = false;
102
84
  }
85
+ // we cannot just test screen size as some smartphones/website meta tags will report desktop resolutions
86
+ // Note: for some reason jasmine fucks up if you put this in the main Plugin function with the rest of these declarations
87
+ // Note: to target Android Mobiles (and not Tablets), we must find "Android" and "Mobile"
88
+ this.isMobile = /Android.+Mobile|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
89
+ // we return these deferred objects from the _init() call so they can be watched, and then we resolve them when each specific request returns
90
+ // Note: again, jasmine had a spazz when I put these in the Plugin function
91
+ this.autoCountryDeferred = new $.Deferred();
92
+ this.utilsScriptDeferred = new $.Deferred();
103
93
  // process all the data: onlyCountries, preferredCountries etc
104
94
  this._processCountryData();
105
95
  // generate the markup
@@ -108,6 +98,10 @@ https://github.com/Bluefieldscom/intl-tel-input.git
108
98
  this._setInitialState();
109
99
  // start all of the event listeners: autoHideDialCode, input keydown, selectedFlag click
110
100
  this._initListeners();
101
+ // utils script, and auto country
102
+ this._initRequests();
103
+ // return the deferreds
104
+ return [ this.autoCountryDeferred, this.utilsScriptDeferred ];
111
105
  },
112
106
  /********************
113
107
  * PRIVATE METHODS
@@ -132,6 +126,11 @@ https://github.com/Bluefieldscom/intl-tel-input.git
132
126
  var i;
133
127
  // process onlyCountries option
134
128
  if (this.options.onlyCountries.length) {
129
+ // standardise case
130
+ for (i = 0; i < this.options.onlyCountries.length; i++) {
131
+ this.options.onlyCountries[i] = this.options.onlyCountries[i].toLowerCase();
132
+ }
133
+ // build instance country array
135
134
  this.countries = [];
136
135
  for (i = 0; i < allCountries.length; i++) {
137
136
  if ($.inArray(allCountries[i].iso2, this.options.onlyCountries) != -1) {
@@ -160,7 +159,7 @@ https://github.com/Bluefieldscom/intl-tel-input.git
160
159
  _setPreferredCountries: function() {
161
160
  this.preferredCountries = [];
162
161
  for (var i = 0; i < this.options.preferredCountries.length; i++) {
163
- var countryCode = this.options.preferredCountries[i], countryData = this._getCountryData(countryCode, false, true);
162
+ var countryCode = this.options.preferredCountries[i].toLowerCase(), countryData = this._getCountryData(countryCode, false, true);
164
163
  if (countryData) {
165
164
  this.preferredCountries.push(countryData);
166
165
  }
@@ -176,58 +175,73 @@ https://github.com/Bluefieldscom/intl-tel-input.git
176
175
  this.telInput.wrap($("<div>", {
177
176
  "class": "intl-tel-input"
178
177
  }));
179
- var flagsContainer = $("<div>", {
178
+ this.flagsContainer = $("<div>", {
180
179
  "class": "flag-dropdown"
181
- }).insertAfter(this.telInput);
180
+ }).insertBefore(this.telInput);
182
181
  // currently selected flag (displayed to left of input)
183
182
  var selectedFlag = $("<div>", {
183
+ // make element focusable and tab naviagable
184
+ tabindex: "0",
184
185
  "class": "selected-flag"
185
- }).appendTo(flagsContainer);
186
+ }).appendTo(this.flagsContainer);
186
187
  this.selectedFlagInner = $("<div>", {
187
188
  "class": "iti-flag"
188
189
  }).appendTo(selectedFlag);
189
190
  // CSS triangle
190
191
  $("<div>", {
191
192
  "class": "arrow"
192
- }).appendTo(this.selectedFlagInner);
193
- // country list contains: preferred countries, then divider, then all countries
194
- this.countryList = $("<ul>", {
195
- "class": "country-list v-hide"
196
- }).appendTo(flagsContainer);
197
- if (this.preferredCountries.length) {
198
- this._appendListItems(this.preferredCountries, "preferred");
199
- $("<li>", {
200
- "class": "divider"
201
- }).appendTo(this.countryList);
193
+ }).appendTo(selectedFlag);
194
+ // country list
195
+ // mobile is just a native select element
196
+ // desktop is a proper list containing: preferred countries, then divider, then all countries
197
+ if (this.isMobile) {
198
+ this.countryList = $("<select>", {
199
+ "class": "iti-mobile-select"
200
+ }).appendTo(this.flagsContainer);
201
+ } else {
202
+ this.countryList = $("<ul>", {
203
+ "class": "country-list v-hide"
204
+ }).appendTo(this.flagsContainer);
205
+ if (this.preferredCountries.length && !this.isMobile) {
206
+ this._appendListItems(this.preferredCountries, "preferred");
207
+ $("<li>", {
208
+ "class": "divider"
209
+ }).appendTo(this.countryList);
210
+ }
202
211
  }
203
212
  this._appendListItems(this.countries, "");
204
- // now we can grab the dropdown height, and hide it properly
205
- this.dropdownHeight = this.countryList.outerHeight();
206
- this.countryList.removeClass("v-hide").addClass("hide");
207
- // on small screens make the dropdown the same width as the input
208
- if (window.innerWidth < 500) {
209
- this.countryList.outerWidth(this.telInput.outerWidth());
213
+ if (!this.isMobile) {
214
+ // now we can grab the dropdown height, and hide it properly
215
+ this.dropdownHeight = this.countryList.outerHeight();
216
+ this.countryList.removeClass("v-hide").addClass("hide");
217
+ // this is useful in lots of places
218
+ this.countryListItems = this.countryList.children(".country");
210
219
  }
211
- // this is useful in lots of places
212
- this.countryListItems = this.countryList.children(".country");
213
220
  },
214
221
  // add a country <li> to the countryList <ul> container
222
+ // UPDATE: if isMobile, add an <option> to the countryList <select> container
215
223
  _appendListItems: function(countries, className) {
216
- // we create so many DOM elements, I decided it was faster to build a temp string
224
+ // we create so many DOM elements, it is faster to build a temp string
217
225
  // and then add everything to the DOM in one go at the end
218
226
  var tmp = "";
219
227
  // for each country
220
228
  for (var i = 0; i < countries.length; i++) {
221
229
  var c = countries[i];
222
- // open the list item
223
- tmp += "<li class='country " + className + "' data-dial-code='" + c.dialCode + "' data-country-code='" + c.iso2 + "'>";
224
- // add the flag
225
- tmp += "<div class='iti-flag " + c.iso2 + "'></div>";
226
- // and the country name and dial code
227
- tmp += "<span class='country-name'>" + c.name + "</span>";
228
- tmp += "<span class='dial-code'>+" + c.dialCode + "</span>";
229
- // close the list item
230
- tmp += "</li>";
230
+ if (this.isMobile) {
231
+ tmp += "<option data-dial-code='" + c.dialCode + "' value='" + c.iso2 + "'>";
232
+ tmp += c.name + " +" + c.dialCode;
233
+ tmp += "</option>";
234
+ } else {
235
+ // open the list item
236
+ tmp += "<li class='country " + className + "' data-dial-code='" + c.dialCode + "' data-country-code='" + c.iso2 + "'>";
237
+ // add the flag
238
+ tmp += "<div class='flag'><div class='iti-flag " + c.iso2 + "'></div></div>";
239
+ // and the country name and dial code
240
+ tmp += "<span class='country-name'>" + c.name + "</span>";
241
+ tmp += "<span class='dial-code'>+" + c.dialCode + "</span>";
242
+ // close the list item
243
+ tmp += "</li>";
244
+ }
231
245
  }
232
246
  this.countryList.append(tmp);
233
247
  },
@@ -236,25 +250,24 @@ https://github.com/Bluefieldscom/intl-tel-input.git
236
250
  var val = this.telInput.val();
237
251
  // if there is a number, and it's valid, we can go ahead and set the flag, else fall back to default
238
252
  if (this._getDialCode(val)) {
239
- this._updateFlagFromNumber(val);
240
- } else {
241
- var defaultCountry;
253
+ this._updateFlagFromNumber(val, true);
254
+ } else if (this.options.defaultCountry != "auto") {
242
255
  // check the defaultCountry option, else fall back to the first in the list
243
256
  if (this.options.defaultCountry) {
244
- defaultCountry = this._getCountryData(this.options.defaultCountry, false, false);
257
+ this.options.defaultCountry = this._getCountryData(this.options.defaultCountry.toLowerCase(), false, false);
245
258
  } else {
246
- defaultCountry = this.preferredCountries.length ? this.preferredCountries[0] : this.countries[0];
259
+ this.options.defaultCountry = this.preferredCountries.length ? this.preferredCountries[0] : this.countries[0];
247
260
  }
248
- this._selectFlag(defaultCountry.iso2);
261
+ this._selectFlag(this.options.defaultCountry.iso2);
249
262
  // if empty, insert the default dial code (this function will check !nationalMode and !autoHideDialCode)
250
263
  if (!val) {
251
- this._updateDialCode(defaultCountry.dialCode, false);
264
+ this._updateDialCode(this.options.defaultCountry.dialCode, false);
252
265
  }
253
266
  }
254
267
  // format
255
268
  if (val) {
256
269
  // this wont be run after _updateDialCode as that's only called if no val
257
- this._updateVal(val, false);
270
+ this._updateVal(val);
258
271
  }
259
272
  },
260
273
  // initialise the main event listeners: input keyup, and click selected flag
@@ -265,28 +278,52 @@ https://github.com/Bluefieldscom/intl-tel-input.git
265
278
  if (this.options.autoHideDialCode || this.options.autoFormat) {
266
279
  this._initFocusListeners();
267
280
  }
268
- // 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
269
- var label = this.telInput.closest("label");
270
- if (label.length) {
271
- label.on("click" + this.ns, function(e) {
272
- // if the dropdown is closed, then focus the input, else ignore the click
273
- if (that.countryList.hasClass("hide")) {
274
- that.telInput.focus();
275
- } else {
276
- e.preventDefault();
281
+ if (this.isMobile) {
282
+ this.countryList.on("change" + this.ns, function(e) {
283
+ that._selectListItem($(this).find("option:selected"));
284
+ });
285
+ } else {
286
+ // 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
287
+ var label = this.telInput.closest("label");
288
+ if (label.length) {
289
+ label.on("click" + this.ns, function(e) {
290
+ // if the dropdown is closed, then focus the input, else ignore the click
291
+ if (that.countryList.hasClass("hide")) {
292
+ that.telInput.focus();
293
+ } else {
294
+ e.preventDefault();
295
+ }
296
+ });
297
+ }
298
+ // toggle country dropdown on click
299
+ var selectedFlag = this.selectedFlagInner.parent();
300
+ selectedFlag.on("click" + this.ns, function(e) {
301
+ // only intercept this event if we're opening the dropdown
302
+ // else let it bubble up to the top ("click-off-to-close" listener)
303
+ // we cannot just stopPropagation as it may be needed to close another instance
304
+ if (that.countryList.hasClass("hide") && !that.telInput.prop("disabled") && !that.telInput.prop("readonly")) {
305
+ that._showDropdown();
277
306
  }
278
307
  });
279
308
  }
280
- // toggle country dropdown on click
281
- var selectedFlag = this.selectedFlagInner.parent();
282
- selectedFlag.on("click" + this.ns, function(e) {
283
- // only intercept this event if we're opening the dropdown
284
- // else let it bubble up to the top ("click-off-to-close" listener)
285
- // we cannot just stopPropagation as it may be needed to close another instance
286
- if (that.countryList.hasClass("hide") && !that.telInput.prop("disabled") && !that.telInput.prop("readonly")) {
309
+ // open dropdown list if currently focused
310
+ this.flagsContainer.on("keydown" + that.ns, function(e) {
311
+ var isDropdownHidden = that.countryList.hasClass("hide");
312
+ if (isDropdownHidden && (e.which == keys.UP || e.which == keys.DOWN || e.which == keys.SPACE || e.which == keys.ENTER)) {
313
+ // prevent form from being submitted if "ENTER" was pressed
314
+ e.preventDefault();
315
+ // prevent event from being handled again by document
316
+ e.stopPropagation();
287
317
  that._showDropdown();
288
318
  }
319
+ // allow navigation from dropdown to input on TAB
320
+ if (e.which == keys.TAB) {
321
+ that._closeDropdown();
322
+ }
289
323
  });
324
+ },
325
+ _initRequests: function() {
326
+ var that = this;
290
327
  // if the user has specified the path to the utils script, fetch it on window.load
291
328
  if (this.options.utilsScript) {
292
329
  // if the plugin is being initialised after the window.load event has already been fired
@@ -298,6 +335,44 @@ https://github.com/Bluefieldscom/intl-tel-input.git
298
335
  that.loadUtils();
299
336
  });
300
337
  }
338
+ } else {
339
+ this.utilsScriptDeferred.resolve();
340
+ }
341
+ if (this.options.defaultCountry == "auto") {
342
+ this._loadAutoCountry();
343
+ } else {
344
+ this.autoCountryDeferred.resolve();
345
+ }
346
+ },
347
+ _loadAutoCountry: function() {
348
+ var that = this;
349
+ // check for cookie
350
+ var cookieAutoCountry = $.cookie ? $.cookie("itiAutoCountry") : "";
351
+ if (cookieAutoCountry) {
352
+ $.fn[pluginName].autoCountry = cookieAutoCountry;
353
+ }
354
+ // 3 options:
355
+ // 1) already loaded (we're done)
356
+ // 2) not already started loading (start)
357
+ // 3) already started loading (do nothing - just wait for loading callback to fire)
358
+ if ($.fn[pluginName].autoCountry) {
359
+ this.autoCountryLoaded();
360
+ } else if (!$.fn[pluginName].startedLoadingAutoCountry) {
361
+ // don't do this twice!
362
+ $.fn[pluginName].startedLoadingAutoCountry = true;
363
+ if (typeof this.options.geoIpLookup === "function") {
364
+ this.options.geoIpLookup(function(countryCode) {
365
+ $.fn[pluginName].autoCountry = countryCode.toLowerCase();
366
+ if ($.cookie) {
367
+ $.cookie("itiAutoCountry", $.fn[pluginName].autoCountry, {
368
+ path: "/"
369
+ });
370
+ }
371
+ // tell all instances the auto country is ready
372
+ // TODO: this should just be the current instances
373
+ $(".intl-tel-input input").intlTelInput("autoCountryLoaded");
374
+ });
375
+ }
301
376
  }
302
377
  },
303
378
  _initKeyListeners: function() {
@@ -311,8 +386,9 @@ https://github.com/Bluefieldscom/intl-tel-input.git
311
386
  // 32 is space, and after that it's all chars (not meta/nav keys)
312
387
  // this fix is needed for Firefox, which triggers keypress event for some meta/nav keys
313
388
  // Update: also ignore if this is a metaKey e.g. FF and Safari trigger keypress on the v of Ctrl+v
389
+ // Update: also ignore if ctrlKey (FF on Windows/Ubuntu)
314
390
  // Update: also check that we have utils before we do any autoFormat stuff
315
- if (e.which >= keys.SPACE && !e.metaKey && window.intlTelInputUtils && !that.telInput.prop("readonly")) {
391
+ if (e.which >= keys.SPACE && !e.ctrlKey && !e.metaKey && window.intlTelInputUtils && !that.telInput.prop("readonly")) {
316
392
  e.preventDefault();
317
393
  // allowed keys are just numeric keys and plus
318
394
  // 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
@@ -322,58 +398,88 @@ https://github.com/Bluefieldscom/intl-tel-input.git
322
398
  // 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
323
399
  if (isBelowMax && (isAllowedKey || noSelection)) {
324
400
  var newChar = isAllowedKey ? String.fromCharCode(e.which) : null;
325
- that._handleInputKey(newChar, true);
401
+ that._handleInputKey(newChar, true, isAllowedKey);
326
402
  // if something has changed, trigger the input event (which was otherwised squashed by the preventDefault)
327
403
  if (val != that.telInput.val()) {
328
404
  that.telInput.trigger("input");
329
405
  }
330
406
  }
331
407
  if (!isAllowedKey) {
332
- that.telInput.trigger("invalidkey");
408
+ that._handleInvalidKey();
333
409
  }
334
410
  }
335
411
  });
336
412
  }
413
+ // handle cut/paste event (now supported in all major browsers)
414
+ this.telInput.on("cut" + this.ns + " paste" + this.ns, function() {
415
+ // hack because "paste" event is fired before input is updated
416
+ setTimeout(function() {
417
+ if (that.options.autoFormat && window.intlTelInputUtils) {
418
+ var cursorAtEnd = that.isGoodBrowser && that.telInput[0].selectionStart == that.telInput.val().length;
419
+ that._handleInputKey(null, cursorAtEnd);
420
+ that._ensurePlus();
421
+ } else {
422
+ // if no autoFormat, just update flag
423
+ that._updateFlagFromNumber(that.telInput.val());
424
+ }
425
+ });
426
+ });
337
427
  // handle keyup event
338
- // for autoFormat: we use keyup to catch cut/paste events and also delete events (after the fact)
428
+ // if autoFormat enabled: we use keyup to catch delete events (after the fact)
429
+ // if no autoFormat, this is used to update the flag
339
430
  this.telInput.on("keyup" + this.ns, function(e) {
340
431
  // 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).
341
432
  // ALSO: ignore keyup if readonly
342
433
  if (e.which == keys.ENTER || that.telInput.prop("readonly")) {} else if (that.options.autoFormat && window.intlTelInputUtils) {
343
- var isCtrl = e.which == keys.CTRL || e.which == keys.CMD1 || e.which == keys.CMD2, input = that.telInput[0], // noSelection defaults to false for bad browsers, else would be reformatting on all ctrl keys e.g. select-all/copy
344
- noSelection = that.isGoodBrowser && input.selectionStart == input.selectionEnd, // cursorAtEnd defaults to false for bad browsers else they would never get a reformat on delete
345
- cursorAtEnd = that.isGoodBrowser && input.selectionStart == that.telInput.val().length;
346
- // if delete in the middle: reformat with no suffix (no need to reformat if delete at end)
347
- // if backspace: reformat with no suffix (need to reformat if at end to remove any lingering suffix - this is a feature)
348
- // if ctrl and no selection (i.e. could have just been a paste): reformat (if cursorAtEnd: add suffix)
349
- if (e.which == keys.DEL && !cursorAtEnd || e.which == keys.BSPACE || isCtrl && noSelection) {
434
+ // cursorAtEnd defaults to false for bad browsers else they would never get a reformat on delete
435
+ var cursorAtEnd = that.isGoodBrowser && that.telInput[0].selectionStart == that.telInput.val().length;
436
+ if (!that.telInput.val()) {
437
+ // if they just cleared the input, update the flag to the default
438
+ that._updateFlagFromNumber("");
439
+ } else if (e.which == keys.DEL && !cursorAtEnd || e.which == keys.BSPACE) {
440
+ // if delete in the middle: reformat with no suffix (no need to reformat if delete at end)
441
+ // if backspace: reformat with no suffix (need to reformat if at end to remove any lingering suffix - this is a feature)
350
442
  // 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
351
- that._handleInputKey(null, isCtrl && cursorAtEnd);
352
- }
353
- // prevent deleting the plus (if not in nationalMode)
354
- if (!that.options.nationalMode) {
355
- var val = that.telInput.val();
356
- if (val.substr(0, 1) != "+") {
357
- // newCursorPos is current pos + 1 to account for the plus we are about to add
358
- var newCursorPos = that.isGoodBrowser ? input.selectionStart + 1 : 0;
359
- that.telInput.val("+" + val);
360
- if (that.isGoodBrowser) {
361
- input.setSelectionRange(newCursorPos, newCursorPos);
362
- }
363
- }
443
+ that._handleInputKey();
364
444
  }
445
+ that._ensurePlus();
365
446
  } else {
366
447
  // if no autoFormat, just update flag
367
448
  that._updateFlagFromNumber(that.telInput.val());
368
449
  }
369
450
  });
370
451
  },
371
- // when autoFormat is enabled: handle various key events on the input: the 2 main situations are 1) adding a new number character, which will replace any selection, reformat, and preserve the cursor position. and 2) reformatting on backspace, or paste event (etc)
372
- _handleInputKey: function(newNumericChar, addSuffix) {
373
- var val = this.telInput.val(), numericBefore = this._getNumeric(val), originalLeftChar, // raw DOM element
452
+ // prevent deleting the plus (if not in nationalMode)
453
+ _ensurePlus: function() {
454
+ if (!this.options.nationalMode) {
455
+ var val = this.telInput.val(), input = this.telInput[0];
456
+ if (val.charAt(0) != "+") {
457
+ // newCursorPos is current pos + 1 to account for the plus we are about to add
458
+ var newCursorPos = this.isGoodBrowser ? input.selectionStart + 1 : 0;
459
+ this.telInput.val("+" + val);
460
+ if (this.isGoodBrowser) {
461
+ input.setSelectionRange(newCursorPos, newCursorPos);
462
+ }
463
+ }
464
+ }
465
+ },
466
+ // alert the user to an invalid key event
467
+ _handleInvalidKey: function() {
468
+ var that = this;
469
+ this.telInput.trigger("invalidkey").addClass("iti-invalid-key");
470
+ setTimeout(function() {
471
+ that.telInput.removeClass("iti-invalid-key");
472
+ }, 100);
473
+ },
474
+ // when autoFormat is enabled: handle various key events on the input:
475
+ // 1) adding a new number character, which will replace any selection, reformat, and preserve the cursor position
476
+ // 2) reformatting on backspace/delete
477
+ // 3) cut/paste event
478
+ _handleInputKey: function(newNumericChar, addSuffix, isAllowedKey) {
479
+ var val = this.telInput.val(), cleanBefore = this._getClean(val), originalLeftChars, // raw DOM element
374
480
  input = this.telInput[0], digitsOnRight = 0;
375
481
  if (this.isGoodBrowser) {
376
- // 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 digits if paste event), and B) we're always on the right side of formatting suffixes
482
+ // 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
377
483
  digitsOnRight = this._getDigitsOnRight(val, input.selectionEnd);
378
484
  // if handling a new number character: insert it in the right place
379
485
  if (newNumericChar) {
@@ -381,27 +487,18 @@ https://github.com/Bluefieldscom/intl-tel-input.git
381
487
  val = val.substr(0, input.selectionStart) + newNumericChar + val.substring(input.selectionEnd, val.length);
382
488
  } else {
383
489
  // 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.
384
- originalLeftChar = val.charAt(input.selectionStart - 1);
490
+ // UPDATE: now have to store 2 chars as extensions formatting contains 2 spaces so you need to be able to distinguish
491
+ originalLeftChars = val.substr(input.selectionStart - 2, 2);
385
492
  }
386
493
  } else if (newNumericChar) {
387
494
  val += newNumericChar;
388
495
  }
389
496
  // update the number and flag
390
- this.setNumber(val, addSuffix);
391
- val = this.telInput.val();
392
- var numericAfter = this._getNumeric(val), numericIsSame = numericBefore == numericAfter;
393
- if (this.options.preventInvalidNumbers && newNumericChar) {
394
- if (numericIsSame) {
395
- // if we're trying to add a new numeric char and the numeric digits haven't changed, then trigger invalid
396
- this.telInput.trigger("invalidkey");
397
- } else if (numericBefore.length == numericAfter.length) {
398
- // preventInvalidNumbers edge case: adding digit in middle of full number, so a digit gets dropped from the end (numeric digits have changed but are same length)
399
- digitsOnRight--;
400
- }
401
- }
497
+ this.setNumber(val, null, addSuffix, true, isAllowedKey);
402
498
  // update the cursor position
403
499
  if (this.isGoodBrowser) {
404
500
  var newCursor;
501
+ val = this.telInput.val();
405
502
  // if it was at the end, keep it there
406
503
  if (!digitsOnRight) {
407
504
  newCursor = val.length;
@@ -410,18 +507,18 @@ https://github.com/Bluefieldscom/intl-tel-input.git
410
507
  newCursor = this._getCursorFromDigitsOnRight(val, digitsOnRight);
411
508
  // but if delete/paste etc, keep going left until hit the same left char as before
412
509
  if (!newNumericChar) {
413
- newCursor = this._getCursorFromLeftChar(val, newCursor, originalLeftChar);
510
+ newCursor = this._getCursorFromLeftChar(val, newCursor, originalLeftChars);
414
511
  }
415
512
  }
416
513
  // set the new cursor
417
514
  input.setSelectionRange(newCursor, newCursor);
418
515
  }
419
516
  },
420
- // we start from the position in guessCursor, and work our way left until we hit the originalLeftChar 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
421
- _getCursorFromLeftChar: function(val, guessCursor, originalLeftChar) {
517
+ // 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
518
+ _getCursorFromLeftChar: function(val, guessCursor, originalLeftChars) {
422
519
  for (var i = guessCursor; i > 0; i--) {
423
520
  var leftChar = val.charAt(i - 1);
424
- if (leftChar == originalLeftChar || $.isNumeric(leftChar)) {
521
+ if ($.isNumeric(leftChar) || val.substr(i - 2, 2) == originalLeftChars) {
425
522
  return i;
426
523
  }
427
524
  }
@@ -466,8 +563,8 @@ https://github.com/Bluefieldscom/intl-tel-input.git
466
563
  // save this to compare on blur
467
564
  that.telInput.data("focusVal", value);
468
565
  // on focus: if empty, insert the dial code for the currently selected flag
469
- if (that.options.autoHideDialCode && !value && !that.telInput.prop("readonly")) {
470
- that._updateVal("+" + that.selectedCountryData.dialCode, true);
566
+ if (that.options.autoHideDialCode && !value && !that.telInput.prop("readonly") && that.selectedCountryData.dialCode) {
567
+ that._updateVal("+" + that.selectedCountryData.dialCode, null, true);
471
568
  // 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
472
569
  that.telInput.one("keypress.plus" + that.ns, function(e) {
473
570
  if (e.which == keys.PLUS) {
@@ -489,7 +586,7 @@ https://github.com/Bluefieldscom/intl-tel-input.git
489
586
  this.telInput.on("blur" + this.ns, function() {
490
587
  if (that.options.autoHideDialCode) {
491
588
  // on blur: if just a dial code then remove it
492
- var value = that.telInput.val(), startsPlus = value.substr(0, 1) == "+";
589
+ var value = that.telInput.val(), startsPlus = value.charAt(0) == "+";
493
590
  if (startsPlus) {
494
591
  var numeric = that._getNumeric(value);
495
592
  // if just a plus, or if just a dial code
@@ -510,15 +607,23 @@ https://github.com/Bluefieldscom/intl-tel-input.git
510
607
  _getNumeric: function(s) {
511
608
  return s.replace(/\D/g, "");
512
609
  },
610
+ _getClean: function(s) {
611
+ var prefix = s.charAt(0) == "+" ? "+" : "";
612
+ return prefix + this._getNumeric(s);
613
+ },
513
614
  // show the dropdown
514
615
  _showDropdown: function() {
515
616
  this._setDropdownPosition();
516
617
  // update highlighting and scroll to active list item
517
618
  var activeListItem = this.countryList.children(".active");
518
- this._highlightListItem(activeListItem);
619
+ if (activeListItem.length) {
620
+ this._highlightListItem(activeListItem);
621
+ }
519
622
  // show it
520
623
  this.countryList.removeClass("hide");
521
- this._scrollTo(activeListItem);
624
+ if (activeListItem.length) {
625
+ this._scrollTo(activeListItem);
626
+ }
522
627
  // bind all the dropdown-related listeners: mouseover, click, click-off, keydown
523
628
  this._bindDropdownListeners();
524
629
  // update the arrow
@@ -625,10 +730,20 @@ https://github.com/Bluefieldscom/intl-tel-input.git
625
730
  },
626
731
  // update the input's value to the given val
627
732
  // if autoFormat=true, format it first according to the country-specific formatting rules
628
- _updateVal: function(val, addSuffix) {
733
+ // Note: preventConversion will be false (i.e. we allow conversion) on init and when dev calls public method setNumber
734
+ _updateVal: function(val, format, addSuffix, preventConversion, isAllowedKey) {
629
735
  var formatted;
630
- if (this.options.autoFormat && window.intlTelInputUtils) {
631
- formatted = intlTelInputUtils.formatNumber(val, this.selectedCountryData.iso2, addSuffix, this.options.preventInvalidNumbers);
736
+ if (this.options.autoFormat && window.intlTelInputUtils && this.selectedCountryData) {
737
+ if (typeof format == "number" && intlTelInputUtils.isValidNumber(val, this.selectedCountryData.iso2)) {
738
+ // if user specified a format, and it's a valid number, then format it accordingly
739
+ formatted = intlTelInputUtils.formatNumberByType(val, this.selectedCountryData.iso2, format);
740
+ } else if (!preventConversion && this.options.nationalMode && val.charAt(0) == "+" && intlTelInputUtils.isValidNumber(val, this.selectedCountryData.iso2)) {
741
+ // if nationalMode and we have a valid intl number, convert it to ntl
742
+ formatted = intlTelInputUtils.formatNumberByType(val, this.selectedCountryData.iso2, intlTelInputUtils.numberFormat.NATIONAL);
743
+ } else {
744
+ // else do the regular AsYouType formatting
745
+ formatted = intlTelInputUtils.formatNumber(val, this.selectedCountryData.iso2, addSuffix, this.options.allowExtensions, isAllowedKey);
746
+ }
632
747
  // ensure we dont go over maxlength. we must do this here to truncate any formatting suffix, and also handle paste events
633
748
  var max = this.telInput.attr("maxlength");
634
749
  if (max && formatted.length > max) {
@@ -641,34 +756,40 @@ https://github.com/Bluefieldscom/intl-tel-input.git
641
756
  this.telInput.val(formatted);
642
757
  },
643
758
  // check if need to select a new flag based on the given number
644
- _updateFlagFromNumber: function(number) {
759
+ _updateFlagFromNumber: function(number, updateDefault) {
645
760
  // 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
646
761
  // 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
647
- if (this.options.nationalMode && this.selectedCountryData && this.selectedCountryData.dialCode == "1" && number.substr(0, 1) != "+") {
648
- number = "+1" + number;
762
+ if (number && this.options.nationalMode && this.selectedCountryData && this.selectedCountryData.dialCode == "1" && number.charAt(0) != "+") {
763
+ if (number.charAt(0) != "1") {
764
+ number = "1" + number;
765
+ }
766
+ number = "+" + number;
649
767
  }
650
768
  // try and extract valid dial code from input
651
- var dialCode = this._getDialCode(number);
769
+ var dialCode = this._getDialCode(number), countryCode = null;
652
770
  if (dialCode) {
653
771
  // check if one of the matching countries is already selected
654
- var countryCodes = this.countryCodes[this._getNumeric(dialCode)], alreadySelected = false;
655
- if (this.selectedCountryData) {
656
- for (var i = 0; i < countryCodes.length; i++) {
657
- if (countryCodes[i] == this.selectedCountryData.iso2) {
658
- alreadySelected = true;
659
- }
660
- }
661
- }
772
+ var countryCodes = this.countryCodes[this._getNumeric(dialCode)], alreadySelected = this.selectedCountryData && $.inArray(this.selectedCountryData.iso2, countryCodes) != -1;
662
773
  // if a matching country is not already selected (or this is an unknown NANP area code): choose the first in the list
663
774
  if (!alreadySelected || this._isUnknownNanp(number, dialCode)) {
664
775
  // if using onlyCountries option, countryCodes[0] may be empty, so we must find the first non-empty index
665
776
  for (var j = 0; j < countryCodes.length; j++) {
666
777
  if (countryCodes[j]) {
667
- this._selectFlag(countryCodes[j]);
778
+ countryCode = countryCodes[j];
668
779
  break;
669
780
  }
670
781
  }
671
782
  }
783
+ } else if (number.charAt(0) == "+" && this._getNumeric(number).length) {
784
+ // invalid dial code, so empty
785
+ // Note: use getNumeric here because the number has not been formatted yet, so could contain bad shit
786
+ countryCode = "";
787
+ } else if (!number || number == "+") {
788
+ // empty, or just a plus, so default
789
+ countryCode = this.options.defaultCountry.iso2;
790
+ }
791
+ if (countryCode !== null) {
792
+ this._selectFlag(countryCode, updateDefault);
672
793
  }
673
794
  },
674
795
  // 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
@@ -696,38 +817,57 @@ https://github.com/Bluefieldscom/intl-tel-input.git
696
817
  }
697
818
  },
698
819
  // select the given flag, update the placeholder and the active list item
699
- _selectFlag: function(countryCode) {
820
+ _selectFlag: function(countryCode, updateDefault) {
700
821
  // do this first as it will throw an error and stop if countryCode is invalid
701
- this.selectedCountryData = this._getCountryData(countryCode, false, false);
822
+ this.selectedCountryData = countryCode ? this._getCountryData(countryCode, false, false) : {};
823
+ // update the "defaultCountry" - we only need the iso2 from now on, so just store that
824
+ if (updateDefault && this.selectedCountryData.iso2) {
825
+ // can't just make this equal to selectedCountryData as would be a ref to that object
826
+ this.options.defaultCountry = {
827
+ iso2: this.selectedCountryData.iso2
828
+ };
829
+ }
702
830
  this.selectedFlagInner.attr("class", "iti-flag " + countryCode);
703
831
  // update the selected country's title attribute
704
- var title = this.selectedCountryData.name + ": +" + this.selectedCountryData.dialCode;
832
+ var title = countryCode ? this.selectedCountryData.name + ": +" + this.selectedCountryData.dialCode : "Unknown";
705
833
  this.selectedFlagInner.parent().attr("title", title);
706
834
  // and the input's placeholder
707
835
  this._updatePlaceholder();
708
- // update the active list item
709
- var listItem = this.countryListItems.children(".iti-flag." + countryCode).first().parent();
710
- this.countryListItems.removeClass("active");
711
- listItem.addClass("active");
836
+ if (this.isMobile) {
837
+ this.countryList.val(countryCode);
838
+ } else {
839
+ // update the active list item
840
+ this.countryListItems.removeClass("active");
841
+ if (countryCode) {
842
+ this.countryListItems.find(".iti-flag." + countryCode).first().closest(".country").addClass("active");
843
+ }
844
+ }
712
845
  },
713
846
  // update the input placeholder to an example number from the currently selected country
714
847
  _updatePlaceholder: function() {
715
- if (window.intlTelInputUtils && !this.hadInitialPlaceholder) {
716
- var iso2 = this.selectedCountryData.iso2, numberType = intlTelInputUtils.numberType[this.options.numberType || "FIXED_LINE"], placeholder = intlTelInputUtils.getExampleNumber(iso2, this.options.nationalMode, numberType);
848
+ if (window.intlTelInputUtils && !this.hadInitialPlaceholder && this.options.autoPlaceholder && this.selectedCountryData) {
849
+ var iso2 = this.selectedCountryData.iso2, numberType = intlTelInputUtils.numberType[this.options.numberType || "FIXED_LINE"], placeholder = iso2 ? intlTelInputUtils.getExampleNumber(iso2, this.options.nationalMode, numberType) : "";
717
850
  this.telInput.attr("placeholder", placeholder);
718
851
  }
719
852
  },
720
853
  // called when the user selects a list item from the dropdown
721
854
  _selectListItem: function(listItem) {
855
+ var countryCodeAttr = this.isMobile ? "value" : "data-country-code";
722
856
  // update selected flag and active list item
723
- var countryCode = listItem.attr("data-country-code");
724
- this._selectFlag(countryCode);
725
- this._closeDropdown();
857
+ this._selectFlag(listItem.attr(countryCodeAttr), true);
858
+ if (!this.isMobile) {
859
+ this._closeDropdown();
860
+ }
726
861
  this._updateDialCode(listItem.attr("data-dial-code"), true);
727
862
  // 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.
728
863
  this.telInput.trigger("change");
729
864
  // focus the input
730
865
  this.telInput.focus();
866
+ // 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
867
+ if (this.isGoodBrowser) {
868
+ var len = this.telInput.val().length;
869
+ this.telInput[0].setSelectionRange(len, len);
870
+ }
731
871
  },
732
872
  // close the dropdown and unbind any listeners
733
873
  _closeDropdown: function() {
@@ -765,7 +905,7 @@ https://github.com/Bluefieldscom/intl-tel-input.git
765
905
  var inputVal = this.telInput.val(), newNumber;
766
906
  // save having to pass this every time
767
907
  newDialCode = "+" + newDialCode;
768
- if (this.options.nationalMode && inputVal.substr(0, 1) != "+") {
908
+ if (this.options.nationalMode && inputVal.charAt(0) != "+") {
769
909
  // if nationalMode, we just want to re-format
770
910
  newNumber = inputVal;
771
911
  } else if (inputVal) {
@@ -776,13 +916,13 @@ https://github.com/Bluefieldscom/intl-tel-input.git
776
916
  newNumber = inputVal.replace(prevDialCode, newDialCode);
777
917
  } else {
778
918
  // if the previous number didn't contain a dial code, we should persist it
779
- var existingNumber = inputVal.substr(0, 1) != "+" ? $.trim(inputVal) : "";
919
+ var existingNumber = inputVal.charAt(0) != "+" ? $.trim(inputVal) : "";
780
920
  newNumber = newDialCode + existingNumber;
781
921
  }
782
922
  } else {
783
923
  newNumber = !this.options.autoHideDialCode || focusing ? newDialCode : "";
784
924
  }
785
- this._updateVal(newNumber, focusing);
925
+ this._updateVal(newNumber, null, focusing);
786
926
  },
787
927
  // try and extract a valid international dial code from a full telephone number
788
928
  // Note: returns the raw string inc plus character and any whitespace/dots etc
@@ -814,20 +954,39 @@ https://github.com/Bluefieldscom/intl-tel-input.git
814
954
  /********************
815
955
  * PUBLIC METHODS
816
956
  ********************/
957
+ // this is called when the geoip call returns
958
+ autoCountryLoaded: function() {
959
+ if (this.options.defaultCountry == "auto") {
960
+ this.options.defaultCountry = $.fn[pluginName].autoCountry;
961
+ this._setInitialState();
962
+ this.autoCountryDeferred.resolve();
963
+ }
964
+ },
817
965
  // remove plugin
818
966
  destroy: function() {
819
- // make sure the dropdown is closed (and unbind listeners)
820
- this._closeDropdown();
967
+ if (!this.isMobile) {
968
+ // make sure the dropdown is closed (and unbind listeners)
969
+ this._closeDropdown();
970
+ }
821
971
  // key events, and focus/blur events if autoHideDialCode=true
822
972
  this.telInput.off(this.ns);
823
- // click event to open dropdown
824
- this.selectedFlagInner.parent().off(this.ns);
825
- // label click hack
826
- this.telInput.closest("label").off(this.ns);
973
+ if (this.isMobile) {
974
+ // change event on select country
975
+ this.countryList.off(this.ns);
976
+ } else {
977
+ // click event to open dropdown
978
+ this.selectedFlagInner.parent().off(this.ns);
979
+ // label click hack
980
+ this.telInput.closest("label").off(this.ns);
981
+ }
827
982
  // remove markup
828
983
  var container = this.telInput.parent();
829
984
  container.before(this.telInput).remove();
830
985
  },
986
+ // extract the phone number extension if present
987
+ getExtension: function() {
988
+ return this.telInput.val().split(" ext. ")[1] || "";
989
+ },
831
990
  // format the number to the given type
832
991
  getNumber: function(type) {
833
992
  if (window.intlTelInputUtils) {
@@ -856,15 +1015,15 @@ https://github.com/Bluefieldscom/intl-tel-input.git
856
1015
  },
857
1016
  // validate the input val - assumes the global function isValidNumber (from utilsScript)
858
1017
  isValidNumber: function() {
859
- var val = $.trim(this.telInput.val()), countryCode = this.options.nationalMode ? this.selectedCountryData.iso2 : "", // libphonenumber allows alpha chars, but in order to allow that, we'd need a method to retrieve the processed number, with letters replaced with numbers
860
- containsAlpha = /[a-zA-Z]/.test(val);
861
- if (!containsAlpha && window.intlTelInputUtils) {
1018
+ var val = $.trim(this.telInput.val()), countryCode = this.options.nationalMode ? this.selectedCountryData.iso2 : "";
1019
+ if (window.intlTelInputUtils) {
862
1020
  return intlTelInputUtils.isValidNumber(val, countryCode);
863
1021
  }
864
1022
  return false;
865
1023
  },
866
1024
  // load the utils script
867
1025
  loadUtils: function(path) {
1026
+ var that = this;
868
1027
  var utilsScript = path || this.options.utilsScript;
869
1028
  if (!$.fn[pluginName].loadedUtilsScript && utilsScript) {
870
1029
  // 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)
@@ -876,28 +1035,34 @@ https://github.com/Bluefieldscom/intl-tel-input.git
876
1035
  // tell all instances the utils are ready
877
1036
  $(".intl-tel-input input").intlTelInput("utilsLoaded");
878
1037
  },
1038
+ complete: function() {
1039
+ that.utilsScriptDeferred.resolve();
1040
+ },
879
1041
  dataType: "script",
880
1042
  cache: true
881
1043
  });
1044
+ } else {
1045
+ this.utilsScriptDeferred.resolve();
882
1046
  }
883
1047
  },
884
1048
  // update the selected flag, and update the input val accordingly
885
1049
  selectCountry: function(countryCode) {
1050
+ countryCode = countryCode.toLowerCase();
886
1051
  // check if already selected
887
1052
  if (!this.selectedFlagInner.hasClass(countryCode)) {
888
- this._selectFlag(countryCode);
1053
+ this._selectFlag(countryCode, true);
889
1054
  this._updateDialCode(this.selectedCountryData.dialCode, false);
890
1055
  }
891
1056
  },
892
1057
  // set the input value and update the flag
893
- setNumber: function(number, addSuffix) {
1058
+ setNumber: function(number, format, addSuffix, preventConversion, isAllowedKey) {
894
1059
  // ensure starts with plus
895
- if (!this.options.nationalMode && number.substr(0, 1) != "+") {
1060
+ if (!this.options.nationalMode && number.charAt(0) != "+") {
896
1061
  number = "+" + number;
897
1062
  }
898
1063
  // we must update the flag first, which updates this.selectedCountryData, which is used later for formatting the number before displaying it
899
1064
  this._updateFlagFromNumber(number);
900
- this._updateVal(number, addSuffix);
1065
+ this._updateVal(number, format, addSuffix, preventConversion, isAllowedKey);
901
1066
  },
902
1067
  // this is called when the utils are ready
903
1068
  utilsLoaded: function() {
@@ -915,12 +1080,20 @@ https://github.com/Bluefieldscom/intl-tel-input.git
915
1080
  // Is the first parameter an object (options), or was omitted,
916
1081
  // instantiate a new instance of the plugin.
917
1082
  if (options === undefined || typeof options === "object") {
918
- return this.each(function() {
1083
+ var deferreds = [];
1084
+ this.each(function() {
919
1085
  if (!$.data(this, "plugin_" + pluginName)) {
920
- $.data(this, "plugin_" + pluginName, new Plugin(this, options));
1086
+ var instance = new Plugin(this, options);
1087
+ var instanceDeferreds = instance._init();
1088
+ // we now have 2 deffereds: 1 for auto country, 1 for utils script
1089
+ deferreds.push(instanceDeferreds[0]);
1090
+ deferreds.push(instanceDeferreds[1]);
1091
+ $.data(this, "plugin_" + pluginName, instance);
921
1092
  }
922
1093
  });
923
- } else if (typeof options === "string" && options[0] !== "_" && options !== "init") {
1094
+ // return the promise from the "master" deferred object that tracks all the others
1095
+ return $.when.apply(null, deferreds);
1096
+ } else if (typeof options === "string" && options[0] !== "_") {
924
1097
  // If the first parameter is a string and it doesn't start
925
1098
  // with an underscore or "contains" the `init`-function,
926
1099
  // treat this as a call to a public method.
@@ -952,6 +1125,7 @@ https://github.com/Bluefieldscom/intl-tel-input.git
952
1125
  $.fn[pluginName].getCountryData = function() {
953
1126
  return allCountries;
954
1127
  };
1128
+ $.fn[pluginName].version = "6.0.4";
955
1129
  // Tell JSHint to ignore this warning: "character may get silently deleted by one or more browsers"
956
1130
  // jshint -W100
957
1131
  // Array of country objects for the flag dropdown.