1/* 2International Telephone Input v6.0.0 3https://github.com/Bluefieldscom/intl-tel-input.git 4*/ 5// wrap in UMD - see https://github.com/umdjs/umd/blob/master/jqueryPlugin.js 6(function(factory) { 7 if (typeof define === "function" && define.amd) { 8 define([ "jquery" ], function($) { 9 factory($, window, document); 10 }); 11 } else { 12 factory(jQuery, window, document); 13 } 14})(function($, window, document, undefined) { 15 "use strict"; 16 // these vars persist through all instances of the plugin 17 var pluginName = "intlTelInput", id = 1, // give each instance it's own id for namespaced event handling 18 defaults = { 19 // typing digits after a valid number will be added to the extension part of the number 20 allowExtensions: false, 21 // automatically format the number according to the selected country 22 autoFormat: true, 23 // add or remove input placeholder with an example number for the selected country 24 autoPlaceholder: true, 25 // if there is just a dial code in the input: remove it on blur, and re-add it on focus 26 autoHideDialCode: true, 27 // default country 28 defaultCountry: "", 29 // geoIp lookup function 30 geoIpLookup: null, 31 // don't insert international dial codes 32 nationalMode: true, 33 // number type to use for placeholders 34 numberType: "MOBILE", 35 // display only these countries 36 onlyCountries: [], 37 // the countries at the top of the list. defaults to united states and united kingdom 38 preferredCountries: [ "us", "gb" ], 39 // specify the path to the libphonenumber script to enable validation/formatting 40 utilsScript: "" 41 }, keys = { 42 UP: 38, 43 DOWN: 40, 44 ENTER: 13, 45 ESC: 27, 46 PLUS: 43, 47 A: 65, 48 Z: 90, 49 ZERO: 48, 50 NINE: 57, 51 SPACE: 32, 52 BSPACE: 8, 53 TAB: 9, 54 DEL: 46, 55 CTRL: 17, 56 CMD1: 91, 57 // Chrome 58 CMD2: 224 59 }, windowLoaded = false; 60 // keep track of if the window.load event has fired as impossible to check after the fact 61 $(window).load(function() { 62 windowLoaded = true; 63 }); 64 function Plugin(element, options) { 65 this.element = element; 66 this.options = $.extend({}, defaults, options); 67 this._defaults = defaults; 68 // event namespace 69 this.ns = "." + pluginName + id++; 70 // Chrome, FF, Safari, IE9+ 71 this.isGoodBrowser = Boolean(element.setSelectionRange); 72 this.hadInitialPlaceholder = Boolean($(element).attr("placeholder")); 73 this._name = pluginName; 74 } 75 Plugin.prototype = { 76 _init: function() { 77 // if in nationalMode, disable options relating to dial codes 78 if (this.options.nationalMode) { 79 this.options.autoHideDialCode = false; 80 } 81 // IE Mobile doesn't support the keypress event (see issue 68) which makes autoFormat impossible 82 if (navigator.userAgent.match(/IEMobile/i)) { 83 this.options.autoFormat = false; 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(); 93 // process all the data: onlyCountries, preferredCountries etc 94 this._processCountryData(); 95 // generate the markup 96 this._generateMarkup(); 97 // set the initial state of the input value and the selected flag 98 this._setInitialState(); 99 // start all of the event listeners: autoHideDialCode, input keydown, selectedFlag click 100 this._initListeners(); 101 // utils script, and auto country 102 this._initRequests(); 103 // return the deferreds 104 return [ this.autoCountryDeferred, this.utilsScriptDeferred ]; 105 }, 106 /******************** 107 * PRIVATE METHODS 108 ********************/ 109 // prepare all of the country data, including onlyCountries and preferredCountries options 110 _processCountryData: function() { 111 // set the instances country data objects 112 this._setInstanceCountryData(); 113 // set the preferredCountries property 114 this._setPreferredCountries(); 115 }, 116 // add a country code to this.countryCodes 117 _addCountryCode: function(iso2, dialCode, priority) { 118 if (!(dialCode in this.countryCodes)) { 119 this.countryCodes[dialCode] = []; 120 } 121 var index = priority || 0; 122 this.countryCodes[dialCode][index] = iso2; 123 }, 124 // process onlyCountries array if present, and generate the countryCodes map 125 _setInstanceCountryData: function() { 126 var i; 127 // process onlyCountries option 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 134 this.countries = []; 135 for (i = 0; i < allCountries.length; i++) { 136 if ($.inArray(allCountries[i].iso2, this.options.onlyCountries) != -1) { 137 this.countries.push(allCountries[i]); 138 } 139 } 140 } else { 141 this.countries = allCountries; 142 } 143 // generate countryCodes map 144 this.countryCodes = {}; 145 for (i = 0; i < this.countries.length; i++) { 146 var c = this.countries[i]; 147 this._addCountryCode(c.iso2, c.dialCode, c.priority); 148 // area codes 149 if (c.areaCodes) { 150 for (var j = 0; j < c.areaCodes.length; j++) { 151 // full dial code is country code + dial code 152 this._addCountryCode(c.iso2, c.dialCode + c.areaCodes[j]); 153 } 154 } 155 } 156 }, 157 // process preferred countries - iterate through the preferences, 158 // fetching the country data for each one 159 _setPreferredCountries: function() { 160 this.preferredCountries = []; 161 for (var i = 0; i < this.options.preferredCountries.length; i++) { 162 var countryCode = this.options.preferredCountries[i].toLowerCase(), countryData = this._getCountryData(countryCode, false, true); 163 if (countryData) { 164 this.preferredCountries.push(countryData); 165 } 166 } 167 }, 168 // generate all of the markup for the plugin: the selected flag overlay, and the dropdown 169 _generateMarkup: function() { 170 // telephone input 171 this.telInput = $(this.element); 172 // 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 c
172ould mean the wrong number is saved (esp in nationalMode) 173 this.telInput.attr("autocomplete", "off"); 174 // containers (mostly for positioning) 175 this.telInput.wrap($("<div>", { 176 "class": "intl-tel-input" 177 })); 178 this.flagsContainer = $("<div>", { 179 "class": "flag-dropdown" 180 }).insertBefore(this.telInput); 181 // currently selected flag (displayed to left of input) 182 var selectedFlag = $("<div>", { 183 // make element focusable and tab naviagable 184 tabindex: "0", 185 "class": "selected-flag" 186 }).appendTo(this.flagsContainer); 187 this.selectedFlagInner = $("<div>", { 188 "class": "iti-flag" 189 }).appendTo(selectedFlag); 190 // CSS triangle 191 $("<div>", { 192 "class": "arrow" 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 } 211 } 212 this._appendListItems(this.countries, ""); 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"); 219 } 220 }, 221 // add a country <li> to the countryList <ul> container 222 // UPDATE: if isMobile, add an <option> to the countryList <select> container 223 _appendListItems: function(countries, className) { 224 // we create so many DOM elements, it is faster to build a temp string 225 // and then add everything to the DOM in one go at the end 226 var tmp = ""; 227 // for each country 228 for (var i = 0; i < countries.length; i++) { 229 var c = countries[i]; 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 } 245 } 246 this.countryList.append(tmp); 247 }, 248 // set the initial state of the input value and the selected flag 249 _setInitialState: function() { 250 var val = this.telInput.val(); 251 // if there is a number, and it's valid, we can go ahead and set the flag, else fall back to default 252 if (this._getDialCode(val)) { 253 this._updateFlagFromNumber(val, true); 254 } else if (this.options.defaultCountry != "auto") { 255 // check the defaultCountry option, else fall back to the first in the list 256 if (this.options.defaultCountry) { 257 this.options.defaultCountry = this._getCountryData(this.options.defaultCountry.toLowerCase(), false, false); 258 } else { 259 this.options.defaultCountry = this.preferredCountries.length ? this.preferredCountries[0] : this.countries[0]; 260 } 261 this._selectFlag(this.options.defaultCountry.iso2); 262 // if empty, insert the default dial code (this function will check !nationalMode and !autoHideDialCode) 263 if (!val) { 264 this._updateDialCode(this.options.defaultCountry.dialCode, false); 265 } 266 } 267 // format 268 if (val) { 269 // this wont be run after _updateDialCode as that's only called
269if no val 270 this._updateVal(val); 271 } 272 }, 273 // initialise the main event listeners: input keyup, and click selected flag 274 _initListeners: function() { 275 var that = this; 276 this._initKeyListeners(); 277 // autoFormat prevents the change event from firing, so we need to check for changes between focus and blur in order to manually trigger it 278 if (this.options.autoHideDialCode || this.options.autoFormat) { 279 this._initFocusListeners(); 280 } 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(); 306 } 307 }); 308 } 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(); 317 that._showDropdown(); 318 } 319 // allow navigation from dropdown to input on TAB 320 if (e.which == keys.TAB) { 321 that._closeDropdown(); 322 } 323 }); 324 }, 325 _initRequests: function() { 326 var that = this; 327 // if the user has specified the path to the utils script, fetch it on window.load 328 if (this.options.utilsScript) { 329 // if the plugin is being initialised after the window.load event has already been fired 330 if (windowLoaded) { 331 this.loadUtils(); 332 } else { 333 // wait until the load event so we don't block any other requests e.g. the flags image 334 $(window).load(function() { 335 that.loadUtils(); 336 }); 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 } 376 } 377 }, 378 _initKeyListeners: function() { 379 var that = this; 380 if (this.options.autoFormat) { 381 // format number and update flag on keypress 382 // use keypress event as we want to ignore all input except for a select few keys, 383 // but we dont want to ignore the navigation keys like the arrows etc. 384 // NOTE: no point in refactoring this to only bind these listeners on focus/blur because then you would need to have those 2 listeners running the whole time anyway... 385 this.telInput.on("keypress" + this.ns, function(e) { 386 // 32 is space, and after that it's all chars (not meta/nav keys) 387 // this fix is needed for Firefox, which triggers keypress event for some meta/nav keys 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) 390 // Update: also check that we have utils before we do any autoFormat stuff 391 if (e.which >= keys.SPACE && !e.ctrlKey && !e.metaKey && window.intlTelInputUtils && !that.telInput.prop("readonly")) { 392 e.preventDefault(); 393 // allowed keys are just numeric keys and plus 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 395 var isAllowedKey = e.which >= keys.ZERO && e.which <= keys.NINE || e.which == keys.PLUS, input = that.telInput[0], noSelection = that.isGoodBrowser && input.selectionStart == input.selectionEnd, max = that.telInput.attr("maxlength"), val = that.telInput.val(), // assumes that if max exists, it is >0 396 isBelowMax = max ? val.length < max : true; 397 // first: ensure we dont go over maxlength. we must do this here to prevent adding digits in the middle of the number 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 399 if (isBelowMax && (isAllowedKey || noSelection)) { 400 var newChar = isAllowedKey ? String.fromCharCode(e.which) : null; 401 that._handleInputKey(newChar, true, isAllowedKey
401); 402 // if something has changed, trigger the input event (which was otherwised squashed by the preventDefault) 403 if (val != that.telInput.val()) { 404 that.telInput.trigger("input"); 405 } 406 } 407 if (!isAllowedKey) { 408 that._handleInvalidKey(); 409 } 410 } 411 }); 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 }); 427 // handle keyup event 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 430 this.telInput.on("keyup" + this.ns, function(e) { 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). 432 // ALSO: ignore keyup if readonly 433 if (e.which == keys.ENTER || that.telInput.prop("readonly")) {} else if (that.options.autoFormat && window.intlTelInputUtils) { 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) 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 443 that._handleInputKey(); 444 } 445 that._ensurePlus(); 446 } else { 447 // if no autoFormat, just update flag 448 that._updateFlagFromNumber(that.telInput.val()); 449 } 450 }); 451 }, 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 480 input = this.telInput[0], digitsOnRight = 0; 481 if (this.isGoodBrowser) { 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 483 digitsOnRight = this._getDigitsOnRight(val, input.selectionEnd); 484 // if handling a new number character: insert it in the right place 485 if (newNumericChar) { 486 // replace any selection they may have made with the new char 487 val = val.substr(0, input.selectionStart) + newNumericChar + val.substring(input.selectionEnd, val.length); 488 } else { 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. 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); 492 } 493 } else if (newNumericChar) { 494 val += newNumericChar; 495 } 496 // update the number and flag 497 this.setNumber(val, null, addSuffix, true, isAllowedKey); 498 // update the cursor position 499 if (this.isGoodBrowser) { 500 var newCursor; 501 val = this.telInput.val(); 502 // if it was at the end, keep it there 503 if (!digitsOnRight) { 504 newCursor = val.length; 505 } else { 506 // else count in the same number of digits from the right 507 newCursor = this._getCursorFromDigitsOnRight(val, digitsOnRight); 508 // but if delete/paste etc, keep going left until hit the same left char as before 509 if (!newNumericChar) { 510 newCursor = this._getCursorFromLeftChar(val, newCursor, originalLeftChars); 511 } 512 } 513 // set the new cursor 514 input.setSelectionRange(newCursor, newCursor); 515 } 516 }, 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) { 519 for (var i = guessCursor; i > 0; i--) { 520 var leftChar = val.charAt(i - 1); 521 if ($.isNumeric(leftChar) || val.substr(i - 2, 2) == originalLeftChars) { 522 return i; 523 } 524 } 525 return 0; 526 }, 527 // after a reformat we need to make sure there are still the same number of digits to the right of the cursor 528 _getCursorFromDigitsOnRight: function(val, digitsOnRight) { 529 for (var i = val.length - 1; i >= 0; i--) { 530 if ($.isNumeric(val.charAt(i))) { 531 if (--digitsOnRight === 0) { 532 return i; 533 } 534 } 535 } 536 return 0; 537 }, 538 // get the number of numeric digits to the right of the cursor so we can reposition the cursor correctly after the reformat has happened 539 _getDigitsOnRight: function(val, selectionEnd) { 540 var digitsOnRight = 0; 541 for (var i = selectionEnd; i < val.length; i++) { 542 if ($.isNumeric(val.charAt(i))) { 543 digitsOnRight++; 544 } 545 } 546 return digitsOnRight; 547 }, 548 // listen for focus and blur 549 _initFocusListeners: function() { 550 var that = this; 551 if (this.options.autoHideDialCode) { 552 // 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 553 this.telInput.on("mousedown" + this.ns, function(e) { 554 if (!that.telInput.is(":focus") && !that.telInput.val()) { 555 e.preventDefault(); 556 // but this also cancels the focus, so we must trigger that manually 557 that.telInput.focus(); 558 } 559 }); 560 } 561 this.telInput.on("focus" + this.ns, function(e) { 562 var value = that.telInput.val(); 563 // save this to compare on blur 564 that.telInput.data("focusVal", value); 565 // on focus: if empty, insert the dial code for the currently selected flag 566 if (that.options.autoHideDialCode && !value && !that.telInput.prop("readonly") && that.selectedCountryData.dialCode) {
567 that._updateVal("+" + that.selectedCountryData.dialCode, null, true); 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 569 that.telInput.one("keypress.plus" + that.ns, function(e) { 570 if (e.which == keys.PLUS) { 571 // if autoFormat is enabled, this key event will have already have been handled by another keypress listener (hence we need to add the "+"). if disabled, it will be handled after this by a keyup listener (hence no need to add the "+"). 572 var newVal = that.options.autoFormat && window.intlTelInputUtils ? "+" : ""; 573 that.telInput.val(newVal); 574 } 575 }); 576 // 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 577 setTimeout(function() { 578 var input = that.telInput[0]; 579 if (that.isGoodBrowser) { 580 var len = that.telInput.val().length; 581 input.setSelectionRange(len, len); 582 } 583 }); 584 } 585 }); 586 this.telInput.on("blur" + this.ns, function() { 587 if (that.options.autoHideDialCode) { 588 // on blur: if just a dial code then remove it 589 var value = that.telInput.val(), startsPlus = value.charAt(0) == "+"; 590 if (startsPlus) { 591 var numeric = that._getNumeric(value); 592 // if just a plus, or if just a dial code 593 if (!numeric || that.selectedCountryData.dialCode == numeric) { 594 that.telInput.val(""); 595 } 596 } 597 // remove the keypress listener we added on focus 598 that.telInput.off("keypress.plus" + that.ns); 599 } 600 // if autoFormat, we must manually trigger change event if value has changed 601 if (that.options.autoFormat && window.intlTelInputUtils && that.telInput.val() != that.telInput.data("focusVal")) { 602 that.telInput.trigger("change"); 603 } 604 }); 605 }, 606 // extract the numeric digits from the given string 607 _getNumeric: function(s) { 608 return s.replace(/\D/g, ""); 609 }, 610 _getClean: function(s) { 611 var prefix = s.charAt(0) == "+" ? "+" : ""; 612 return prefix + this._getNumeric(s); 613 }, 614 // show the dropdown 615 _showDropdown: function() { 616 this._setDropdownPosition(); 617 // update highlighting and scroll to active list item 618 var activeListItem = this.countryList.children(".active"); 619 if (activeListItem.length) { 620 this._highlightListItem(activeListItem); 621 } 622 // show it 623 this.countryList.removeClass("hide"); 624 if (activeListItem.length) { 625 this._scrollTo(activeListItem); 626 } 627 // bind all the dropdown-related listeners: mouseover, click, click-off, keydown 628 this._bindDropdownListeners(); 629 // update the arrow 630 this.selectedFlagInner.children(".arrow").addClass("up"); 631 }, 632 // decide where to position dropdown (depends on position within viewport, and scroll) 633 _setDropdownPosition: function() { 634 var inputTop = this.telInput.offset().top, windowTop = $(window).scrollTop(), // dropdownFitsBelow = (dropdownBottom < windowBottom) 635 dropdownFitsBelow = inputTop + this.telInput.outerHeight() + this.dropdownHeight < windowTop + $(window).height(), dropdownFitsAbove = inputTop - this.dropdownHeight > windowTop; 636 // dropdownHeight - 1 for border 637 var cssTop = !dropdownFitsBelow && dropdownFitsAbove ? "-" + (this.dropdownHeight - 1) + "px" : ""; 638 this.countryList.css("top", cssTop); 639 }, 640 // we only bind dropdown listeners when the dropdown is open 641 _bindDropdownListeners: function() { 642 var that = this; 643 // when mouse over a list item, just highlight that one 644 // we add the class "highlight", so if they hit "enter" we know
644which one to select 645 this.countryList.on("mouseover" + this.ns, ".country", function(e) { 646 that._highlightListItem($(this)); 647 }); 648 // listen for country selection 649 this.countryList.on("click" + this.ns, ".country", function(e) { 650 that._selectListItem($(this)); 651 }); 652 // click off to close 653 // (except when this initial opening click is bubbling up) 654 // we cannot just stopPropagation as it may be needed to close another instance 655 var isOpening = true; 656 $("html").on("click" + this.ns, function(e) { 657 if (!isOpening) { 658 that._closeDropdown(); 659 } 660 isOpening = false; 661 }); 662 // listen for up/down scrolling, enter to select, or letters to jump to country name. 663 // use keydown as keypress doesn't fire for non-char keys and we want to catch if they 664 // just hit down and hold it to scroll down (no keyup event). 665 // listen on the document because that's where key events are triggered if no input has focus 666 var query = "", queryTimer = null; 667 $(document).on("keydown" + this.ns, function(e) { 668 // prevent down key from scrolling the whole page, 669 // and enter key from submitting a form etc 670 e.preventDefault(); 671 if (e.which == keys.UP || e.which == keys.DOWN) { 672 // up and down to navigate 673 that._handleUpDownKey(e.which); 674 } else if (e.which == keys.ENTER) { 675 // enter to select 676 that._handleEnterKey(); 677 } else if (e.which == keys.ESC) { 678 // esc to close 679 that._closeDropdown(); 680 } else if (e.which >= keys.A && e.which <= keys.Z || e.which == keys.SPACE) { 681 // upper case letters (note: keyup/keydown only return upper case letters) 682 // jump to countries that start with the query string 683 if (queryTimer) { 684 clearTimeout(queryTimer); 685 } 686 query += String.fromCharCode(e.which); 687 that._searchForCountry(query); 688 // if the timer hits 1 second, reset the query 689 queryTimer = setTimeout(function() { 690 query = ""; 691 }, 1e3); 692 } 693 }); 694 }, 695 // highlight the next/prev item in the list (and ensure it is visible) 696 _handleUpDownKey: function(key) { 697 var current = this.countryList.children(".highlight").first(); 698 var next = key == keys.UP ? current.prev() : current.next(); 699 if (next.length) { 700 // skip the divider 701 if (next.hasClass("divider")) { 702 next = key == keys.UP ? next.prev() : next.next(); 703 } 704 this._highlightListItem(next); 705 this._scrollTo(next); 706 } 707 }, 708 // select the currently highlighted item 709 _handleEnterKey: function() { 710 var currentCountry = this.countryList.children(".highlight").first(); 711 if (currentCountry.length) { 712 this._selectListItem(currentCountry); 713 } 714 }, 715 // find the first list item whose name starts with the query string 716 _searchForCountry: function(query) { 717 for (var i = 0; i < this.countries.length; i++) { 718 if (this._startsWith(this.countries[i].name, query)) { 719 var listItem = this.countryList.children("[data-country-code=" + this.countries[i].iso2 + "]").not(".preferred"); 720 // update highlighting and scroll 721 this._highlightListItem(listItem); 722 this._scrollTo(listItem, true); 723 break; 724 } 725 } 726 }, 727 // check if (uppercase) string a starts with string b 728 _startsWith: function(a, b) { 729 return a.substr(0, b.length).toUpperCase() == b; 730 }, 731 // update the input's value to the given val 732 // if autoFormat=true, format it first according to the country-specific formatting rules 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) { 735 var formatted; 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 } 747 // ensure we dont go over maxlength. we must do this here to truncate any formatting suffix, and also handle paste events 748 var max = this.telInput.attr("maxlength"); 749 if (max && formatted.length > max) { 750 formatted = formatted.substr(0, max); 751 } 752 } else { 753 // no autoFormat, so just insert the original value 754 formatted = val; 755 } 756 this.telInput.val(formatted); 757 }, 758 // check if need to select a new flag based on the given number 759 _updateFlagFromNumber: function(number, updateDefault) { 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 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 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; 767 } 768 // try and extract valid dial code from input 769 var dialCode = this._getDialCode(number), countryCode = null; 770 if (dialCode) { 771 // check if one of the matching countries is already selected 772 var countryCodes = this.countryCodes[this._getNumeric(dialCode)], alreadySelected = this.selectedCountryData && $.inArray(this.selectedCountryData.iso2, countryCodes) != -1; 773 // if a matching country is not already selected (or this is an unknown NANP area code): choose the first in the list 774 if (!alreadySelected || this._isUnknownNanp(number, dialCode)) { 775 // if using onlyCountries option, countryCodes[0] may be empty, so we must find the first non-empty index 776 for (var j = 0; j < countryCodes.length; j++) { 777 if (countryCodes[j]) { 778 countryCode = countryCodes[j]; 779 break; 780 } 781 } 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); 793 } 794 }, 795 // check if the given number contains an unknown area code from the North American Numbering Plan i.e. the only dialCode that c
795ould be extracted was +1 but the actual number's length is >=4 796 _isUnknownNanp: function(number, dialCode) { 797 return dialCode == "+1" && this._getNumeric(number).length >= 4; 798 }, 799 // remove highlighting from other list items and highlight the given item 800 _highlightListItem: function(listItem) { 801 this.countryListItems.removeClass("highlight"); 802 listItem.addClass("highlight"); 803 }, 804 // find the country data for the given country code 805 // the ignoreOnlyCountriesOption is only used during init() while parsing the onlyCountries array 806 _getCountryData: function(countryCode, ignoreOnlyCountriesOption, allowFail) { 807 var countryList = ignoreOnlyCountriesOption ? allCountries : this.countries; 808 for (var i = 0; i < countryList.length; i++) { 809 if (countryList[i].iso2 == countryCode) { 810 return countryList[i]; 811 } 812 } 813 if (allowFail) { 814 return null; 815 } else { 816 throw new Error("No country data for '" + countryCode + "'"); 817 } 818 }, 819 // select the given flag, update the placeholder and the active list item 820 _selectFlag: function(countryCode, updateDefault) { 821 // do this first as it will throw an error and stop if countryCode is invalid 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 } 830 this.selectedFlagInner.attr("class", "iti-flag " + countryCode); 831 // update the selected country's title attribute 832 var title = countryCode ? this.selectedCountryData.name + ": +" + this.selectedCountryData.dialCode : "Unknown"; 833 this.selectedFlagInner.parent().attr("title", title); 834 // and the input's placeholder 835 this._updatePlaceholder(); 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 } 845 }, 846 // update the input placeholder to an example number from the currently selected country 847 _updatePlaceholder: function() { 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) : ""; 850 this.telInput.attr("placeholder", placeholder); 851 } 852 }, 853 // called when the user selects a list item from the dropdown 854 _selectListItem: function(listItem) { 855 var countryCodeAttr = this.isMobile ? "value" : "data-country-code"; 856 // update selected flag and active list item 857 this._selectFlag(listItem.attr(countryCodeAttr), true); 858 if (!this.isMobile) { 859 this._closeDropdown(); 860 } 861 this._updateDialCode(listItem.attr("data-dial-code"), true); 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. 863 this.telInput.trigger("change"); 864 // focus the input 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 } 871 }, 872 // close the dropdown and unbind any listeners 873 _closeDropdown: function() { 874 this.countryList.addClass("hide"); 875 // update the arrow 876 this.selectedFlagInner.children(".arrow").removeClass("up"); 877 // unbind key events 878 $(document).off(this.ns); 879 // unbind click-off-to-close 880 $("html").off(this.ns); 881 // unbind hover and click listeners 882 this.countryList.off(this.ns); 883 }, 884 // check if an element is visible within it's container, else scroll until it is 885 _scrollTo: function(element, middle) { 886 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;
887 if (elementTop < containerTop) { 888 // scroll up 889 if (middle) { 890 newScrollTop -= middleOffset; 891 } 892 container.scrollTop(newScrollTop); 893 } else if (elementBottom > containerBottom) { 894 // scroll down 895 if (middle) { 896 newScrollTop += middleOffset; 897 } 898 var heightDifference = containerHeight - elementHeight; 899 container.scrollTop(newScrollTop - heightDifference); 900 } 901 }, 902 // replace any existing dial code with the new one (if not in nationalMode) 903 // also we need to know if we're focusing for a couple of reasons e.g. if so, we want to add any formatting suffix, also if the input is empty and we're not in nationalMode, then we want to insert the dial code 904 _updateDialCode: function(newDialCode, focusing) { 905 var inputVal = this.telInput.val(), newNumber; 906 // save having to pass this every time 907 newDialCode = "+" + newDialCode; 908 if (this.options.nationalMode && inputVal.charAt(0) != "+") { 909 // if nationalMode, we just want to re-format 910 newNumber = inputVal; 911 } else if (inputVal) { 912 // if the previous number contained a valid dial code, replace it 913 // (if more than just a plus character) 914 var prevDialCode = this._getDialCode(inputVal); 915 if (prevDialCode.length > 1) { 916 newNumber = inputVal.replace(prevDialCode, newDialCode); 917 } else { 918 // if the previous number didn't contain a dial code, we should persist it 919 var existingNumber = inputVal.charAt(0) != "+" ? $.trim(inputVal) : ""; 920 newNumber = newDialCode + existingNumber; 921 } 922 } else { 923 newNumber = !this.options.autoHideDialCode || focusing ? newDialCode : ""; 924 } 925 this._updateVal(newNumber, null, focusing); 926 }, 927 // try and extract a valid international dial code from a full telephone number 928 // Note: returns the raw string inc plus character and any whitespace/dots etc 929 _getDialCode: function(number) { 930 var dialCode = ""; 931 // only interested in international numbers (starting with a plus) 932 if (number.charAt(0) == "+") { 933 var numericChars = ""; 934 // iterate over chars 935 for (var i = 0; i < number.length; i++) { 936 var c = number.charAt(i); 937 // if char is number 938 if ($.isNumeric(c)) { 939 numericChars += c; 940 // if current numericChars make a valid dial code 941 if (this.countryCodes[numericChars]) { 942 // store the actual raw string (useful for matching later) 943 dialCode = number.substr(0, i + 1); 944 } 945 // longest dial code is 4 chars 946 if (numericChars.length == 4) { 947 break; 948 } 949 } 950 } 951 } 952 return dialCode; 953 }, 954 /******************** 955 * PUBLIC METHODS 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 }, 965 // remove plugin 966 destroy: function() { 967 if (!this.isMobile) { 968 // make sure the dropdown is closed (and unbind listeners) 969 this._closeDropdown(); 970 } 971 // key events, and focus/blur events if autoHideDialCode=true 972 this.telInput.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 } 982 // remove markup 983 var container = this.telInput.parent(); 984 container.before(this.telInput).remove(); 985 }, 986 // extract the phone number extension if present 987 getExtension: function() { 988 return this.telInput.val().split(" ext. ")[1] || ""; 989 }, 990 // format the number to the given type 991 getNumber: function(type) { 992 if (window.intlTelInputUtils) { 993 return intlTelInputUtils.formatNumberByType(this.telInput.val(), this.selectedCountryData.iso2, type); 994 } 995 return ""; 996 }, 997 // get the type of the entered number e.g. landline/mobile 998 getNumberType: function() { 999 if (window.intlTelInputUtils) { 1000 return intlTelInputUtils.getNumberType(this.telInput.val(), this.selectedCountryData.iso2); 1001 } 1002 return -99; 1003 }, 1004 // get the country data for the currently selected flag 1005 getSelectedCountryData: function() { 1006 // if this is undefined, the plugin will return it's instance instead, so in that case an empty object makes more sense 1007 return this.selectedCountryData || {}; 1008 }, 1009 // get the validation error 1010 getValidationError: function() { 1011 if (window.intlTelInputUtils) { 1012 return intlTelInputUtils.getValidationError(this.telInput.val(), this.selectedCountryData.iso2); 1013 } 1014 return -99; 1015 }, 1016 // validate the input val - assumes the global function isValidNumber (from utilsScript) 1017 isValidNumber: function() { 1018 var val = $.trim(this.telInput.val()), countryCode = this.options.nationalMode ? this.selectedCountryData.iso2 : ""; 1019 if (window.intlTelInputUtils) { 1020 return intlTelInputUtils.isValidNumber(val, countryCode); 1021 } 1022 return false;
1023 }, 1024 // load the utils script 1025 loadUtils: function(path) { 1026 var that = this; 1027 var utilsScript = path || this.options.utilsScript; 1028 if (!$.fn[pluginName].loadedUtilsScript && utilsScript) { 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) 1030 $.fn[pluginName].loadedUtilsScript = true; 1031 // dont use $.getScript as it prevents caching 1032 $.ajax({ 1033 url: utilsScript, 1034 success: function() { 1035 // tell all instances the utils are ready 1036 $(".intl-tel-input input").intlTelInput("utilsLoaded"); 1037 }, 1038 complete: function() { 1039 that.utilsScriptDeferred.resolve(); 1040 }, 1041 dataType: "script", 1042 cache: true 1043 }); 1044 } else { 1045 this.utilsScriptDeferred.resolve(); 1046 } 1047 }, 1048 // update the selected flag, and update the input val accordingly 1049 selectCountry: function(countryCode) { 1050 countryCode = countryCode.toLowerCase(); 1051 // check if already selected 1052 if (!this.selectedFlagInner.hasClass(countryCode)) { 1053 this._selectFlag(countryCode, true); 1054 this._updateDialCode(this.selectedCountryData.dialCode, false); 1055 } 1056 }, 1057 // set the input value and update the flag 1058 setNumber: function(number, format, addSuffix, preventConversion, isAllowedKey) { 1059 // ensure starts with plus 1060 if (!this.options.nationalMode && number.charAt(0) != "+") { 1061 number = "+" + number; 1062 } 1063 // we must update the flag first, which updates this.selectedCountryData, which is used later for formatting the number before displaying it 1064 this._updateFlagFromNumber(number); 1065 this._updateVal(number, format, addSuffix, preventConversion, isAllowedKey); 1066 }, 1067 // this is called when the utils are ready 1068 utilsLoaded: function() { 1069 // if autoFormat is enabled and there's an initial value in the input, then format it 1070 if (this.options.autoFormat && this.telInput.val()) { 1071 this._updateVal(this.telInput.val()); 1072 } 1073 this._updatePlaceholder(); 1074 } 1075 }; 1076 // adapted to allow public functions 1077 // using https://github.com/jquery-boilerplate/jquery-boilerplate/wiki/Extending-jQuery-Boilerplate 1078 $.fn[pluginName] = function(options) { 1079 var args = arguments; 1080 // Is the first parameter an object (options), or was omitted, 1081 // instantiate a new instance of the plugin. 1082 if (options === undefined || typeof options === "object") { 1083 var deferreds = []; 1084 this.each(function() { 1085 if (!$.data(this, "plugin_" + pluginName)) { 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); 1092 } 1093 }); 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] !== "_") { 1097 // If the first parameter is a string and it doesn't start 1098 // with an underscore or "contains" the `init`-function, 1099 // treat this as a call to a public method. 1100 // Cache the method call to make it possible to return a value 1101 var returns; 1102 this.each(function() { 1103 var instance = $.data(this, "plugin_" + pluginName); 1104 // Tests that there's already a plugin-instance 1105 // and checks that the requested public method exists 1106 if (instance instanceof Plugin && typeof instance[options] === "function") { 1107 // Call the method of our plugin instance, 1108 // and pass it the supplied arguments. 1109 returns = instance[options].apply(instance, Array.prototype.slice.call(args, 1)); 1110 } 1111 // Allow instances to be destroyed via the 'destroy' method 1112 if (options === "destroy") { 1113 $.data(this, "plugin_" + pluginName, null); 1114 } 1115 }); 1116 // If the earlier cached method gives a value back return the value, 1117 // otherwise return this to preserve chainability. 1118 return returns !== undefined ? returns : this; 1119 } 1120 }; 1121 /******************** 1122 * STATIC METHODS 1123 ********************/ 1124 // get the country data object 1125 $.fn[pluginName].getCountryData = function() { 1126 return allCountries; 1127 }; 1128 // Tell JSHint to ignore this warning: "character may get silently deleted by one or more browsers"
1129 // jshint -W100 1130 // Array of country objects for the flag dropdown. 1131 // Each contains a name, country code (ISO 3166-1 alpha-2) and dial code. 1132 // Originally from https://github.com/mledoze/countries 1133 // then modified using the following JavaScript (NOW OUT OF DATE): 1134 /* 1135var result = []; 1136_.each(countries, function(c) { 1137 // ignore countries without a dial code 1138 if (c.callingCode[0].length) { 1139 result.push({ 1140 // var locals contains country names with localised versions in brackets 1141 n: _.findWhere(locals, { 1142 countryCode: c.cca2 1143 }).name, 1144 i: c.cca2.toLowerCase(), 1145 d: c.callingCode[0] 1146 }); 1147 } 1148}); 1149JSON.stringify(result); 1150*/ 1151 // then with a couple of manual re-arrangements to be alphabetical 1152 // then changed Kazakhstan from +76 to +7 1153 // and Vatican City from +379 to +39 (see issue 50) 1154 // and Caribean Netherlands from +5997 to +599 1155 // and Curacao from +5999 to +599 1156 // Removed: Ðâ¦land Islands, Christmas Island, Cocos Islands, Guernsey, Isle of Man, Jersey, Kosovo, Mayotte, Pitcairn Islands, South Georgia, Svalbard, Western Sahara 1157 // Update: converted objects to arrays to save bytes! 1158 // Update: added "priority" for countries with the same dialCode as others 1159 // Update: added array of area codes for countries with the same dialCode as others 1160 // So each country array has the following information: 1161 // [ 1162 // Country name, 1163 // iso2 code, 1164 // International dial code, 1165 // Order (if >1 country with same dial code), 1166 // Area codes (if >1 country with same dial code) 1167 // ] 1168 var allCountries = [ [ "Afghanistan (вÐ«Ш§ЩÐШÑШ§Щâ ШÑШÐШ§Щâ вЬвÐÐ)", "af", "93" ], [ "Albania (ShqipЫri)", "al", "355" ], [ "Algeria (вÐ«Ш§ЩâШ¬ШÐШ§Ш¦Ш±вЬвÐÐ)", "dz", "213" ], [ "American Samoa", "as", "1684" ], [ "Andorra", "ad", "376" ], [ "Angola", "ao", "244" ], [ "Anguilla", "ai", "1264" ], [ "Antigua and Barbuda", "ag", "1268" ], [ "Argentina", "ar", "54" ], [ "Armenia (Ð¥ÐÐ¥ÐХµХÐХРХÑÐ¥ÐХ¶)", "am", "374" ], [ "Aruba", "aw", "297" ], [ "Australia", "au", "61" ], [ "Austria (Ðâsterreich)", "at", "43" ], [ "Azerbaijan (AzÐâ¢rbaycan)", "az", "994" ], [ "Bahamas", "bs", "1242" ], [ "Bahrain (вÐ«Ш§ЩâШÐШÂШ±ЩÐЩâ вЬвÐÐ)", "bh", "973" ], [ "Bangladesh (বа¦Ñа¦âа¦Ðа¦Ñদа§â¡Ð°Â¦Â¶)", "bd", "880" ], [ "Barbados", "bb", "1246" ], [ "Belarus (Ð âелаСÐСÑСÐСÐ)", "by", "375" ], [ "Belgium (BelgiЫ)", "be", "32" ], [ "Belize", "bz", "501" ], [ "Benin (BЩnin)", "bj", "229" ], [ "Bermuda", "bm", "1441" ], [ "Bhutan (аР аРâаÑÐаРÒаРâ)", "bt", "975" ], [ "Bolivia", "bo", "591" ], [ "Bosnia and Herzegovina (Ð âÐ ÑСÐРРР° Ð Ñ Ð ÒРµСÐСâ РµРÑÐ ÑÐ ÐÐ ÑРРР°)", "ba", "387" ], [ "Botswana", "bw", "267" ], [ "Brazil (Brasil)", "br", "55" ], [ "British Indian Ocean Territory", "io", "246" ], [ "British Virgin Islands", "vg", "1284" ], [ "Brunei", "bn", "673" ], [ "Bulgaria (Ð âСÐР»РÑР°СÐÐ ÑСÐ)", "bg", "359" ], [ "Burkina Faso", "bf", "226" ], [ "Burundi (Uburundi)", "bi", "257" ], [ "Cambodia (бÑÐбÑ?бÑâбÑâбÑ»бÑâ¡Ð±Ñ¶)", "kh", "855" ], [ "Cameroon (Cameroun)", "cm", "237" ], [ "Canada", "ca", "1", 1, [ "204", "226", "236", "249", "250", "289", "306", "343", "365", "387", "403", "416", "418", "431", "437", "438", "450", "506", "514", "519", "548", "579", "581", "587", "604", "613", "639", "647", "672", "705", "709", "742", "778", "780", "782", "807", "819", "825", "867", "873", "902", "905" ] ], [ "Cape Verde (Kabu Verdi)", "cv", "238" ], [ "Caribbean Netherlands", "bq", "599", 1 ], [ "Cayman Islands", "ky", "1345" ], [ "Central African Republic (RЩpublique centrafricaine)", "cf", "236" ], [ "Chad (Tchad)", "td", "235" ], [ "Chile", "cl", "56" ], [ "China (дÑÂеâºÐ )", "cn", "86" ], [ "Colombia", "co", "57" ], [ "Comoros (вÐ«Ш¬ШÐШ± Ш§ЩâЩâЩâ¦Ð¨Â±Ð²Ð¬вÐÐ)", "km", "269" ], [ "Congo (DRC) (Jamhuri ya Kidemokrasia ya Kongo)", "cd", "243" ], [ "Congo (Republic) (Congo-Brazzaville)", "cg", "242" ], [ "Cook Islands", "ck", "682" ], [ "Costa Rica", "cr", "506" ], [ "CÐÒte dвÐâ¢Ivoire", "ci", "225" ], [ "Croatia (Hrvatska)", "hr", "385" ], [ "Cuba", "cu", "53" ], [ "CuraЧao", "cw", "599", 0 ], [ "Cyprus (ÐÑÐÐÐÐÐÐÐÑÐâ)", "cy", "357" ], [ "Czech Republic (ÐÐeskÐÐ republika)", "cz", "420" ], [ "Denmark (Danmark)", "dk", "45" ], [ "Djibouti", "dj", "253" ], [ "Dominica", "dm", "1767" ], [ "Dominican Republic (RepÐÑblica Dominicana)", "do", "1", 2, [ "809", "829", "849" ] ], [ "Ecuador", "ec", "593" ], [ "Egypt (вЫЩâ¦Ð¨ÂµÐ¨Â±Ð²Ð¬вÐ
1168Ð)", "eg", "20" ], [ "El Salvador", "sv", "503" ], [ "Equatorial Guinea (Guinea Ecuatorial)", "gq", "240" ], [ "Eritrea", "er", "291" ], [ "Estonia (Eesti)", "ee", "372" ], [ "Ethiopia", "et", "251" ], [ "Falkland Islands (Islas Malvinas)", "fk", "500" ], [ "Faroe Islands (FÐÑroyar)", "fo", "298" ], [ "Fiji", "fj", "679" ], [ "Finland (Suomi)", "fi", "358" ], [ "France", "fr", "33" ], [ "French Guiana (Guyane franЧaise)", "gf", "594" ], [ "French Polynesia (PolynЩsie franЧaise)", "pf", "689" ], [ "Gabon", "ga", "241" ], [ "Gambia", "gm", "220" ], [ "Georgia (бÑÐбÑÑбÑÒбÑÑбÑ бÑâбÑâ¢Ð±ÑâбÑÑбÑÑ)", "ge", "995" ], [ "Germany (Deutschland)", "de", "49" ], [ "Ghana (Gaana)", "gh", "233" ], [ "Gibraltar", "gi", "350" ], [ "Greece (Ðâ¢Ð»Ð»Ð¬ÐÒб)", "gr", "30" ], [ "Greenland (Kalaallit Nunaat)", "gl", "299" ], [ "Grenada", "gd", "1473" ], [ "Guadeloupe", "gp", "590", 0 ], [ "Guam", "gu", "1671" ], [ "Guatemala", "gt", "502" ], [ "Guinea (GuinЩe)", "gn", "224" ], [ "Guinea-Bissau (GuinЩ Bissau)", "gw", "245" ], [ "Guyana", "gy", "592" ], [ "Haiti", "ht", "509" ], [ "Honduras", "hn", "504" ], [ "Hong Kong (й¦â¢Ð¶ÑÐ)", "hk", "852" ], [ "Hungary (MagyarorszÐÐg)", "hu", "36" ], [ "Iceland (ÐÐsland)", "is", "354" ], [ "India (а¤Âа¤Ñरत)", "in", "91" ], [ "Indonesia", "id", "62" ], [ "Iran (вÐ«Ш§ЫÐШ±Ш§Щâ вЬвÐÐ)", "ir", "98" ], [ "Iraq (вÐ«Ш§ЩâШâШ±Ш§ЩâвЬвÐÐ)", "iq", "964" ], [ "Ireland", "ie", "353" ], [ "Israel (вЫЧâ¢Ð§Â©Ð§ÐЧÑЧÑвЬвÐÐ)", "il", "972" ], [ "Italy (Italia)", "it", "39", 0 ], [ "Jamaica", "jm", "1876" ], [ "Japan (жâÒжѬ)", "jp", "81" ], [ "Jordan (вÐ«Ш§ЩâШÐШ±ШÐЩâ вЬвÐÐ)", "jo", "962" ], [ "Kazakhstan (Ð ÑазаСâ¦Ð¡ÐСâР°РÐ
)", "kz", "7", 1 ], [ "Kenya", "ke", "254" ], [ "Kiribati", "ki", "686" ], [ "Kuwait (вÐ«Ш§ЩâЩÑЩâ¬Ð©ÐШÐвЬвÐÐ)", "kw", "965" ], [ "Kyrgyzstan (Ð ÑСâ¹Ð¡ÐÐ ÑСâ¹Ð ·СÐСâР°РÐ
)", "kg", "996" ], [ "Laos (аÑÒаÑÐаѧ)", "la", "856" ], [ "Latvia (Latvija)", "lv", "371" ], [ "Lebanon (вЫЩâШÐЩâ Ш§Щâ вЬвÐÐ)", "lb", "961" ], [ "Lesotho", "ls", "266" ], [ "Liberia", "lr", "231" ], [ "Libya (вЫЩâЩÐШÐЩÐШ§вЬвÐÐ)", "ly", "218" ], [ "Liechtenstein", "li", "423" ], [ "Lithuania (Lietuva)", "lt", "370" ], [ "Luxembourg", "lu", "352" ], [ "Macau (жÑÑйâÐ)", "mo", "853" ], [ "Macedonia (FYROM) (Ð ÑР°РÑРµРÒÐ ÑÐ Ð
Ð ÑС?Р°)", "mk", "389" ], [ "Madagascar (Madagasikara)", "mg", "261" ], [ "Malawi", "mw", "265" ], [ "Malaysia", "my", "60" ], [ "Maldives", "mv", "960" ], [ "Mali", "ml", "223" ], [ "Malta", "mt", "356" ], [ "Marshall Islands", "mh", "692" ], [ "Martinique", "mq", "596" ], [ "Mauritania (вЫЩâ¦Ð©â¬Ð¨Â±Ð©ÐШÐШ§Щâ ЩÐШ§вЬвÐÐ)", "mr", "222" ], [ "Mauritius (Moris)", "mu", "230" ], [ "Mexico (MЩxico)", "mx", "52" ], [ "Micronesia", "fm", "691" ], [ "Moldova (Republica Moldova)", "md", "373" ], [ "Monaco", "mc", "377" ], [ "Mongolia (Ð ÑÐ ÑÐ Ð
Ð ÑÐ ÑР»)", "mn", "976" ], [ "Montenegro (Crna Gora)", "me", "382" ], [ "Montserrat", "ms", "1664" ], [ "Morocco (вÐ«Ш§ЩâЩâ¦Ð¨ÑШ±ШÐвЬвÐÐ)", "ma", "212" ], [ "Mozambique (MoЧambique)", "mz", "258" ], [ "Myanmar (Burma) (бÐâ¢Ð±ÐÑбÐâбÐÑбÐâ¢Ð±Ð¬)", "mm", "95" ], [ "Namibia (NamibiЫ)", "na", "264" ], [ "Nauru", "nr", "674" ], [ "Nepal (а¤ÐаÒâ¡Ð°Â¤Ðа¤Ñа¤Ð)", "np", "977" ], [ "Netherlands (Nederland)", "nl", "31" ], [ "New Caledonia (Nouvelle-CalЩdonie)", "nc", "687" ], [ "New Zealand", "nz", "64" ], [ "Nicaragua", "ni", "505" ], [ "Niger (Nijar)", "ne", "227" ], [ "Nigeria", "ng", "234" ], [ "Niue", "nu", "683" ], [ "Norfolk Island", "nf", "672" ], [ "North Korea (мамâ лÐÑмÐÑмÐÑмÑ? мÑÑлÐÑ ÐºÑµнâ¢âкµÂ)", "kp", "850" ], [ "Northern Mariana Islands", "mp", "1670" ], [ "Norway (Norge)", "no", "47" ], [ "Oman (вЫШâЩÐЩâ¦Ð¨Â§Ð©â вЬвÐÐ)", "om", "968" ], [ "Pakistan (вЫЩÑШ§Ъ©ШÑШÐШ§Щâ вЬвÐ
1168Ð)", "pk", "92" ], [ "Palau", "pw", "680" ], [ "Palestine (вЫЩÐЩâШÑШ·ЩÐЩâ вЬвÐÐ)", "ps", "970" ], [ "Panama (PanamÐÐ)", "pa", "507" ], [ "Papua New Guinea", "pg", "675" ], [ "Paraguay", "py", "595" ], [ "Peru (PerÐÑ)", "pe", "51" ], [ "Philippines", "ph", "63" ], [ "Poland (Polska)", "pl", "48" ], [ "Portugal", "pt", "351" ], [ "Puerto Rico", "pr", "1", 3, [ "787", "939" ] ], [ "Qatar (вЫЩâШ·Ш±вЬвÐÐ)", "qa", "974" ], [ "RЩunion (La RЩunion)", "re", "262" ], [ "Romania (RomÐÑnia)", "ro", "40" ], [ "Russia (Ð Â Ð ÑСÐСÐÐ ÑСÐ)", "ru", "7", 0 ], [ "Rwanda", "rw", "250" ], [ "Saint BarthЩlemy (Saint-BarthЩlemy)", "bl", "590", 1 ], [ "Saint Helena", "sh", "290" ], [ "Saint Kitts and Nevis", "kn", "1869" ], [ "Saint Lucia", "lc", "1758" ], [ "Saint Martin (Saint-Martin (partie franЧaise))", "mf", "590", 2 ], [ "Saint Pierre and Miquelon (Saint-Pierre-et-Miquelon)", "pm", "508" ], [ "Saint Vincent and the Grenadines", "vc", "1784" ], [ "Samoa", "ws", "685" ], [ "San Marino", "sm", "378" ], [ "SÐÐo TomЩ and PrÐÂncipe (SÐÐo TomЩ e PrÐÂncipe)", "st", "239" ], [ "Saudi Arabia (вÐ«Ш§ЩâЩâ¦Ð©â¦Ð©âЩÑШ© Ш§ЩâШâШ±ШÐЩÐШ© Ш§ЩâШÑШâЩâ¬Ð¨ÐЩÐШ©вЬвÐ
1168Ð)", "sa", "966" ], [ "Senegal (SЩnЩgal)", "sn", "221" ], [ "Serbia (Ð ÐСÐР±РÑС?Р°)", "rs", "381" ], [ "Seychelles", "sc", "248" ], [ "Sierra Leone", "sl", "232" ], [ "Singapore", "sg", "65" ], [ "Sint Maarten", "sx", "1721" ], [ "Slovakia (Slovensko)", "sk", "421" ], [ "Slovenia (Slovenija)", "si", "386" ], [ "Solomon Islands", "sb", "677" ], [ "Somalia (Soomaaliya)", "so", "252" ], [ "South Africa", "za", "27" ], [ "South Korea (лÐÐнâ¢ÑлÐÑкµÂ)", "kr", "82" ], [ "South Sudan (вÐ«Ш¬Щâ Щâ¬Ð¨Ð Ш§ЩâШÑЩâ¬Ð¨ÐШ§Щâ вЬвÐÐ)", "ss", "211" ], [ "Spain (Espaбa)", "es", "34" ], [ "Sri Lanka (а·Ðа·ÐвÐÐа¶»а·â а¶Ð
а¶âа¶Ñа·Ðа·Ð)", "lk", "94" ], [ "Sudan (вÐ«Ш§ЩâШÑЩâ¬Ð¨ÐШ§Щâ вЬвÐÐ)", "sd", "249" ], [ "Suriname", "sr", "597" ], [ "Swaziland", "sz", "268" ], [ "Sweden (Sverige)", "se", "46" ], [ "Switzerland (Schweiz)", "ch", "41" ], [ "Syria (вЫШÑЩâ¬Ð¨Â±Ð©ÐШ§вЬвÐÐ)", "sy", "963" ], [ "Taiwan (еазÐÐ)", "tw", "886" ], [ "Tajikistan", "tj", "992" ], [ "Tanzania", "tz", "255" ], [ "Thailand (аââаÑâаÑÑ)", "th", "66" ], [ "Timor-Leste", "tl", "670" ], [ "Togo", "tg", "228" ], [ "Tokelau", "tk", "690" ], [ "Tonga", "to", "676" ], [ "Trinidad and Tobago", "tt", "1868" ], [ "Tunisia (вЫШÐЩâ¬Ð©â ШÑвЬвÐÐ)", "tn", "216" ], [ "Turkey (TÐÑrkiye)", "tr", "90" ], [ "Turkmenistan", "tm", "993" ], [ "Turks and Caicos Islands", "tc", "1649" ], [ "Tuvalu", "tv", "688" ], [ "U.S. Virgin Islands", "vi", "1340" ], [ "Uganda", "ug", "256" ], [ "Ukraine (Ð ÐÐ ÑСÐР°СâÐ Ð
Р°)", "ua", "380" ], [ "United Arab Emirates (вÐ«Ш§ЩâШÒЩâ¦Ð¨Â§Ð¨Â±Ð¨Â§Ð¨Ð Ш§ЩâШâШ±ШÐЩÐШ© Ш§ЩâЩâ¦Ð¨ÐШÂШÐШ©вЬвÐ
1168Ð)", "ae", "971" ], [ "United Kingdom", "gb", "44" ], [ "United States", "us", "1", 0 ], [ "Uruguay", "uy", "598" ], [ "Uzbekistan (Oлzbekiston)", "uz", "998" ], [ "Vanuatu", "vu", "678" ], [ "Vatican City (CittРdel Vaticano)", "va", "39", 1 ], [ "Venezuela", "ve", "58" ], [ "Vietnam (Viб»â¡t Nam)", "vn", "84" ], [ "Wallis and Futuna", "wf", "681" ], [ "Yemen (вÐ«Ш§ЩâЩÐЩâ¦Ð©â вЬвÐÐ)", "ye", "967" ], [ "Zambia", "zm", "260" ], [ "Zimbabwe", "zw", "263" ] ]; 1169 // loop over all of the countries above 1170 for (var i = 0; i < allCountries.length; i++) { 1171 var c = allCountries[i]; 1172 allCountries[i] = { 1173 name: c[0], 1174 iso2: c[1], 1175 dialCode: c[2], 1176 priority: c[3] || 0, 1177 areaCodes: c[4] || null 1178 }; 1179 } 1180});
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.