1/* 2International Telephone Input v6.0.8 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 // if there is just a dial code in the input: remove it on blur, and re-add it on focus 24 autoHideDialCode: true, 25 // add or remove input placeholder with an example number for the selected country 26 autoPlaceholder: 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: "-1", 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 // UPDATE: use setTimeout in case their geoIpLookup function calls this callback straight away (e.g. if they have already done the geo ip lookup somewhere else). Using setTimeout means that the current thread of execution will finish before executing this, which allows the plugin to finish initialising. 374 setTimeout(function() { 375 $(".intl-tel-input input").intlTelInput("autoCountryLoaded"); 376 }); 377 }); 378 } 379 } 380 }, 381 _initKeyListeners: function() { 382 var that = this; 383 if (this.options.autoFormat) { 384 // format number and update flag on keypress 385 // use keypress event as we want to ignore all input except for a select few keys, 386 // but we dont want to ignore the navigation keys like the arrows etc. 387 // 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... 388 this.telInput.on("keypress" + this.ns, function(e) { 389 // 32 is space, and after that it's all chars (not meta/nav keys) 390 // this fix is needed for Firefox, which triggers keypress event for some meta/nav keys 391 // Update: also ignore if this is a metaKey e.g. FF and Safari trigger keypress on the v of Ctrl+v 392 // Update: also ignore if ctrlKey (FF on Windows/Ubuntu) 393 // Update: also check that we have utils before we do any autoFormat stuff 394 if (e.which >= keys.SPACE && !e.ctrlKey && !e.metaKey && window.intlTelInputUtils && !that.telInput.prop("readonly")) { 395 e.preventDefault(); 396 // allowed keys are just numeric keys and plus 397 // 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 398 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 399 isBelowMax = max ? val.length < max : true; 400 // first: ensure we dont go over maxlength. we must do this here to prevent adding digits in the middle of the number 401 // 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 402 if (isBelowMax && (isAllowedKey || noSelection)) { 403 var newChar = isAllowedKey ? String.fromCharCode(e.which) : null; 404 that._handleInputKey(newChar, true, isAllowedKey
404); 405 // if something has changed, trigger the input event (which was otherwised squashed by the preventDefault) 406 if (val != that.telInput.val()) { 407 that.telInput.trigger("input"); 408 } 409 } 410 if (!isAllowedKey) { 411 that._handleInvalidKey(); 412 } 413 } 414 }); 415 } 416 // handle cut/paste event (now supported in all major browsers) 417 this.telInput.on("cut" + this.ns + " paste" + this.ns, function() { 418 // hack because "paste" event is fired before input is updated 419 setTimeout(function() { 420 if (that.options.autoFormat && window.intlTelInputUtils) { 421 var cursorAtEnd = that.isGoodBrowser && that.telInput[0].selectionStart == that.telInput.val().length; 422 that._handleInputKey(null, cursorAtEnd); 423 that._ensurePlus(); 424 } else { 425 // if no autoFormat, just update flag 426 that._updateFlagFromNumber(that.telInput.val()); 427 } 428 }); 429 }); 430 // handle keyup event 431 // if autoFormat enabled: we use keyup to catch delete events (after the fact) 432 // if no autoFormat, this is used to update the flag 433 this.telInput.on("keyup" + this.ns, function(e) { 434 // 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). 435 // ALSO: ignore keyup if readonly 436 if (e.which == keys.ENTER || that.telInput.prop("readonly")) {} else if (that.options.autoFormat && window.intlTelInputUtils) { 437 // cursorAtEnd defaults to false for bad browsers else they would never get a reformat on delete 438 var cursorAtEnd = that.isGoodBrowser && that.telInput[0].selectionStart == that.telInput.val().length; 439 if (!that.telInput.val()) { 440 // if they just cleared the input, update the flag to the default 441 that._updateFlagFromNumber(""); 442 } else if (e.which == keys.DEL && !cursorAtEnd || e.which == keys.BSPACE) { 443 // if delete in the middle: reformat with no suffix (no need to reformat if delete at end) 444 // if backspace: reformat with no suffix (need to reformat if at end to remove any lingering suffix - this is a feature) 445 // 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 446 that._handleInputKey(); 447 } 448 that._ensurePlus(); 449 } else { 450 // if no autoFormat, just update flag 451 that._updateFlagFromNumber(that.telInput.val()); 452 } 453 }); 454 }, 455 // prevent deleting the plus (if not in nationalMode) 456 _ensurePlus: function() { 457 if (!this.options.nationalMode) { 458 var val = this.telInput.val(), input = this.telInput[0]; 459 if (val.charAt(0) != "+") { 460 // newCursorPos is current pos + 1 to account for the plus we are about to add 461 var newCursorPos = this.isGoodBrowser ? input.selectionStart + 1 : 0; 462 this.telInput.val("+" + val); 463 if (this.isGoodBrowser) { 464 input.setSelectionRange(newCursorPos, newCursorPos); 465 } 466 } 467 } 468 },
469 // alert the user to an invalid key event 470 _handleInvalidKey: function() { 471 var that = this; 472 this.telInput.trigger("invalidkey").addClass("iti-invalid-key"); 473 setTimeout(function() { 474 that.telInput.removeClass("iti-invalid-key"); 475 }, 100); 476 }, 477 // when autoFormat is enabled: handle various key events on the input: 478 // 1) adding a new number character, which will replace any selection, reformat, and preserve the cursor position 479 // 2) reformatting on backspace/delete 480 // 3) cut/paste event 481 _handleInputKey: function(newNumericChar, addSuffix, isAllowedKey) { 482 var val = this.telInput.val(), cleanBefore = this._getClean(val), originalLeftChars, // raw DOM element 483 input = this.telInput[0], digitsOnRight = 0; 484 if (this.isGoodBrowser) { 485 // 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 486 digitsOnRight = this._getDigitsOnRight(val, input.selectionEnd); 487 // if handling a new number character: insert it in the right place 488 if (newNumericChar) { 489 // replace any selection they may have made with the new char 490 val = val.substr(0, input.selectionStart) + newNumericChar + val.substring(input.selectionEnd, val.length); 491 } else { 492 // 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. 493 // UPDATE: now have to store 2 chars as extensions formatting contains 2 spaces so you need to be able to distinguish 494 originalLeftChars = val.substr(input.selectionStart - 2, 2); 495 } 496 } else if (newNumericChar) { 497 val += newNumericChar; 498 } 499 // update the number and flag 500 this.setNumber(val, null, addSuffix, true, isAllowedKey); 501 // update the cursor position 502 if (this.isGoodBrowser) { 503 var newCursor; 504 val = this.telInput.val(); 505 // if it was at the end, keep it there 506 if (!digitsOnRight) { 507 newCursor = val.length; 508 } else { 509 // else count in the same number of digits from the right 510 newCursor = this._getCursorFromDigitsOnRight(val, digitsOnRight); 511 // but if delete/paste etc, keep going left until hit the same left char as before 512 if (!newNumericChar) { 513 newCursor = this._getCursorFromLeftChar(val, newCursor, originalLeftChars); 514 } 515 } 516 // set the new cursor 517 input.setSelectionRange(newCursor, newCursor); 518 } 519 }, 520 // 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 521 _getCursorFromLeftChar: function(val, guessCursor, originalLeftChars) { 522 for (var i = guessCursor; i > 0; i--) { 523 var leftChar = val.charAt(i - 1); 524 if ($.isNumeric(leftChar) || val.substr(i - 2, 2) == originalLeftChars) { 525 return i; 526 } 527 } 528 return 0; 529 }, 530 // after a reformat we need to make sure there are still the same number of digits to the right of the cursor 531 _getCursorFromDigitsOnRight: function(val, digitsOnRight) { 532 for (var i = val.length - 1; i >= 0; i--) { 533 if ($.isNumeric(val.charAt(i))) { 534 if (--digitsOnRight === 0) { 535 return i; 536 } 537 } 538 } 539 return 0; 540 }, 541 // get the number of numeric digits to the right of the cursor so we can reposition the cursor correctly after the reformat has happened 542 _getDigitsOnRight: function(val, selectionEnd) { 543 var digitsOnRight = 0; 544 for (var i = selectionEnd; i < val.length; i++) { 545 if ($.isNumeric(val.charAt(i))) { 546 digitsOnRight++; 547 } 548 } 549 return digitsOnRight; 550 }, 551 // listen for focus and blur 552 _initFocusListeners: function() { 553 var that = this; 554 if (this.options.autoHideDialCode) { 555 // 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 556 this.telInput.on("mousedown" + this.ns, function(e) { 557 if (!that.telInput.is(":focus") && !that.telInput.val()) { 558 e.preventDefault(); 559 // but this also cancels the focus, so we must trigger that manually 560 that.telInput.focus(); 561 } 562 }); 563 } 564 this.telInput.on("focus" + this.ns, function(e) { 565 var value = that.telInput.val(); 566 // save this to compare on blur 567 that.telInput.data("focusVal", value); 568 // on focus: if empty, insert the dial code for the currently selected flag 569 if (that.options.autoHideDialCode && !value && !that.telInput.prop("readonly") && that.selectedCountryData.dialCode) {
570 that._updateVal("+" + that.selectedCountryData.dialCode, null, true); 571 // 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 572 that.telInput.one("keypress.plus" + that.ns, function(e) { 573 if (e.which == keys.PLUS) { 574 // 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 "+"). 575 var newVal = that.options.autoFormat && window.intlTelInputUtils ? "+" : ""; 576 that.telInput.val(newVal); 577 } 578 }); 579 // 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 580 setTimeout(function() { 581 var input = that.telInput[0]; 582 if (that.isGoodBrowser) { 583 var len = that.telInput.val().length; 584 input.setSelectionRange(len, len); 585 } 586 }); 587 } 588 }); 589 this.telInput.on("blur" + this.ns, function() { 590 if (that.options.autoHideDialCode) { 591 // on blur: if just a dial code then remove it 592 var value = that.telInput.val(), startsPlus = value.charAt(0) == "+"; 593 if (startsPlus) { 594 var numeric = that._getNumeric(value); 595 // if just a plus, or if just a dial code 596 if (!numeric || that.selectedCountryData.dialCode == numeric) { 597 that.telInput.val(""); 598 } 599 } 600 // remove the keypress listener we added on focus 601 that.telInput.off("keypress.plus" + that.ns); 602 } 603 // if autoFormat, we must manually trigger change event if value has changed 604 if (that.options.autoFormat && window.intlTelInputUtils && that.telInput.val() != that.telInput.data("focusVal")) { 605 that.telInput.trigger("change"); 606 } 607 }); 608 }, 609 // extract the numeric digits from the given string 610 _getNumeric: function(s) { 611 return s.replace(/\D/g, ""); 612 }, 613 _getClean: function(s) { 614 var prefix = s.charAt(0) == "+" ? "+" : ""; 615 return prefix + this._getNumeric(s); 616 }, 617 // show the dropdown 618 _showDropdown: function() { 619 this._setDropdownPosition(); 620 // update highlighting and scroll to active list item 621 var activeListItem = this.countryList.children(".active"); 622 if (activeListItem.length) { 623 this._highlightListItem(activeListItem); 624 } 625 // show it 626 this.countryList.removeClass("hide"); 627 if (activeListItem.length) { 628 this._scrollTo(activeListItem); 629 } 630 // bind all the dropdown-related listeners: mouseover, click, click-off, keydown 631 this._bindDropdownListeners(); 632 // update the arrow 633 this.selectedFlagInner.children(".arrow").addClass("up"); 634 }, 635 // decide where to position dropdown (depends on position within viewport, and scroll) 636 _setDropdownPosition: function() { 637 var inputTop = this.telInput.offset().top, windowTop = $(window).scrollTop(), // dropdownFitsBelow = (dropdownBottom < windowBottom) 638 dropdownFitsBelow = inputTop + this.telInput.outerHeight() + this.dropdownHeight < windowTop + $(window).height(), dropdownFitsAbove = inputTop - this.dropdownHeight > windowTop; 639 // dropdownHeight - 1 for border 640 var cssTop = !dropdownFitsBelow && dropdownFitsAbove ? "-" + (this.dropdownHeight - 1) + "px" : ""; 641 this.countryList.css("top", cssTop); 642 }, 643 // we only bind dropdown listeners when the dropdown is open 644 _bindDropdownListeners: function() { 645 var that = this; 646 // when mouse over a list item, just highlight that one 647 // we add the class "highlight", so if they hit "enter" we know
647which one to select 648 this.countryList.on("mouseover" + this.ns, ".country", function(e) { 649 that._highlightListItem($(this)); 650 }); 651 // listen for country selection 652 this.countryList.on("click" + this.ns, ".country", function(e) { 653 that._selectListItem($(this)); 654 }); 655 // click off to close 656 // (except when this initial opening click is bubbling up) 657 // we cannot just stopPropagation as it may be needed to close another instance 658 var isOpening = true; 659 $("html").on("click" + this.ns, function(e) { 660 if (!isOpening) { 661 that._closeDropdown(); 662 } 663 isOpening = false; 664 }); 665 // listen for up/down scrolling, enter to select, or letters to jump to country name. 666 // use keydown as keypress doesn't fire for non-char keys and we want to catch if they 667 // just hit down and hold it to scroll down (no keyup event). 668 // listen on the document because that's where key events are triggered if no input has focus 669 var query = "", queryTimer = null; 670 $(document).on("keydown" + this.ns, function(e) { 671 // prevent down key from scrolling the whole page, 672 // and enter key from submitting a form etc 673 e.preventDefault(); 674 if (e.which == keys.UP || e.which == keys.DOWN) { 675 // up and down to navigate 676 that._handleUpDownKey(e.which); 677 } else if (e.which == keys.ENTER) { 678 // enter to select 679 that._handleEnterKey(); 680 } else if (e.which == keys.ESC) { 681 // esc to close 682 that._closeDropdown(); 683 } else if (e.which >= keys.A && e.which <= keys.Z || e.which == keys.SPACE) { 684 // upper case letters (note: keyup/keydown only return upper case letters) 685 // jump to countries that start with the query string 686 if (queryTimer) { 687 clearTimeout(queryTimer); 688 } 689 query += String.fromCharCode(e.which); 690 that._searchForCountry(query); 691 // if the timer hits 1 second, reset the query 692 queryTimer = setTimeout(function() { 693 query = ""; 694 }, 1e3); 695 } 696 }); 697 }, 698 // highlight the next/prev item in the list (and ensure it is visible) 699 _handleUpDownKey: function(key) { 700 var current = this.countryList.children(".highlight").first(); 701 var next = key == keys.UP ? current.prev() : current.next(); 702 if (next.length) { 703 // skip the divider 704 if (next.hasClass("divider")) { 705 next = key == keys.UP ? next.prev() : next.next(); 706 } 707 this._highlightListItem(next); 708 this._scrollTo(next); 709 } 710 }, 711 // select the currently highlighted item 712 _handleEnterKey: function() { 713 var currentCountry = this.countryList.children(".highlight").first(); 714 if (currentCountry.length) { 715 this._selectListItem(currentCountry); 716 } 717 }, 718 // find the first list item whose name starts with the query string 719 _searchForCountry: function(query) { 720 for (var i = 0; i < this.countries.length; i++) { 721 if (this._startsWith(this.countries[i].name, query)) { 722 var listItem = this.countryList.children("[data-country-code=" + this.countries[i].iso2 + "]").not(".preferred"); 723 // update highlighting and scroll 724 this._highlightListItem(listItem); 725 this._scrollTo(listItem, true); 726 break; 727 } 728 } 729 }, 730 // check if (uppercase) string a starts with string b 731 _startsWith: function(a, b) { 732 return a.substr(0, b.length).toUpperCase() == b; 733 }, 734 // update the input's value to the given val 735 // if autoFormat=true, format it first according to the country-specific formatting rules 736 // Note: preventConversion will be false (i.e. we allow conversion) on init and when dev calls public method setNumber
737 _updateVal: function(val, format, addSuffix, preventConversion, isAllowedKey) { 738 var formatted; 739 if (this.options.autoFormat && window.intlTelInputUtils && this.selectedCountryData) { 740 if (typeof format == "number" && intlTelInputUtils.isValidNumber(val, this.selectedCountryData.iso2)) { 741 // if user specified a format, and it's a valid number, then format it accordingly 742 formatted = intlTelInputUtils.formatNumberByType(val, this.selectedCountryData.iso2, format); 743 } else if (!preventConversion && this.options.nationalMode && val.charAt(0) == "+" && intlTelInputUtils.isValidNumber(val, this.selectedCountryData.iso2)) { 744 // if nationalMode and we have a valid intl number, convert it to ntl 745 formatted = intlTelInputUtils.formatNumberByType(val, this.selectedCountryData.iso2, intlTelInputUtils.numberFormat.NATIONAL); 746 } else { 747 // else do the regular AsYouType formatting 748 formatted = intlTelInputUtils.formatNumber(val, this.selectedCountryData.iso2, addSuffix, this.options.allowExtensions, isAllowedKey); 749 } 750 // ensure we dont go over maxlength. we must do this here to truncate any formatting suffix, and also handle paste events 751 var max = this.telInput.attr("maxlength"); 752 if (max && formatted.length > max) { 753 formatted = formatted.substr(0, max); 754 } 755 } else { 756 // no autoFormat, so just insert the original value 757 formatted = val; 758 } 759 this.telInput.val(formatted); 760 }, 761 // check if need to select a new flag based on the given number 762 _updateFlagFromNumber: function(number, updateDefault) { 763 // 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 764 // 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 765 if (number && this.options.nationalMode && this.selectedCountryData && this.selectedCountryData.dialCode == "1" && number.charAt(0) != "+") { 766 if (number.charAt(0) != "1") { 767 number = "1" + number; 768 } 769 number = "+" + number; 770 } 771 // try and extract valid dial code from input 772 var dialCode = this._getDialCode(number), countryCode = null; 773 if (dialCode) { 774 // check if one of the matching countries is already selected 775 var countryCodes = this.countryCodes[this._getNumeric(dialCode)], alreadySelected = this.selectedCountryData && $.inArray(this.selectedCountryData.iso2, countryCodes) != -1; 776 // if a matching country is not already selected (or this is an unknown NANP area code): choose the first in the list 777 if (!alreadySelected || this._isUnknownNanp(number, dialCode)) { 778 // if using onlyCountries option, countryCodes[0] may be empty, so we must find the first non-empty index 779 for (var j = 0; j < countryCodes.length; j++) { 780 if (countryCodes[j]) { 781 countryCode = countryCodes[j]; 782 break; 783 } 784 } 785 } 786 } else if (number.charAt(0) == "+" && this._getNumeric(number).length) { 787 // invalid dial code, so empty 788 // Note: use getNumeric here because the number has not been formatted yet, so could contain bad shit 789 countryCode = ""; 790 } else if (!number || number == "+") { 791 // empty, or just a plus, so default 792 countryCode = this.options.defaultCountry.iso2; 793 } 794 if (countryCode !== null) { 795 this._selectFlag(countryCode, updateDefault); 796 } 797 }, 798 // check if the given number contains an unknown area code from the North American Numbering Plan i.e. the only dialCode that c
798ould be extracted was +1 but the actual number's length is >=4 799 _isUnknownNanp: function(number, dialCode) { 800 return dialCode == "+1" && this._getNumeric(number).length >= 4; 801 }, 802 // remove highlighting from other list items and highlight the given item 803 _highlightListItem: function(listItem) { 804 this.countryListItems.removeClass("highlight"); 805 listItem.addClass("highlight"); 806 }, 807 // find the country data for the given country code 808 // the ignoreOnlyCountriesOption is only used during init() while parsing the onlyCountries array 809 _getCountryData: function(countryCode, ignoreOnlyCountriesOption, allowFail) { 810 var countryList = ignoreOnlyCountriesOption ? allCountries : this.countries; 811 for (var i = 0; i < countryList.length; i++) { 812 if (countryList[i].iso2 == countryCode) { 813 return countryList[i]; 814 } 815 } 816 if (allowFail) { 817 return null; 818 } else { 819 throw new Error("No country data for '" + countryCode + "'"); 820 } 821 }, 822 // select the given flag, update the placeholder and the active list item 823 _selectFlag: function(countryCode, updateDefault) { 824 // do this first as it will throw an error and stop if countryCode is invalid 825 this.selectedCountryData = countryCode ? this._getCountryData(countryCode, false, false) : {}; 826 // update the "defaultCountry" - we only need the iso2 from now on, so just store that 827 if (updateDefault && this.selectedCountryData.iso2) { 828 // can't just make this equal to selectedCountryData as would be a ref to that object 829 this.options.defaultCountry = { 830 iso2: this.selectedCountryData.iso2 831 }; 832 } 833 this.selectedFlagInner.attr("class", "iti-flag " + countryCode); 834 // update the selected country's title attribute 835 var title = countryCode ? this.selectedCountryData.name + ": +" + this.selectedCountryData.dialCode : "Unknown"; 836 this.selectedFlagInner.parent().attr("title", title); 837 // and the input's placeholder 838 this._updatePlaceholder(); 839 if (this.isMobile) { 840 this.countryList.val(countryCode); 841 } else { 842 // update the active list item 843 this.countryListItems.removeClass("active"); 844 if (countryCode) { 845 this.countryListItems.find(".iti-flag." + countryCode).first().closest(".country").addClass("active"); 846 } 847 } 848 }, 849 // update the input placeholder to an example number from the currently selected country 850 _updatePlaceholder: function() { 851 if (window.intlTelInputUtils && !this.hadInitialPlaceholder && this.options.autoPlaceholder && this.selectedCountryData) { 852 var iso2 = this.selectedCountryData.iso2, numberType = intlTelInputUtils.numberType[this.options.numberType || "FIXED_LINE"], placeholder = iso2 ? intlTelInputUtils.getExampleNumber(iso2, this.options.nationalMode, numberType) : ""; 853 if (typeof this.options.customPlaceholder === "function") { 854 placeholder = this.options.customPlaceholder(placeholder, this.selectedCountryData); 855 } 856 this.telInput.attr("placeholder", placeholder); 857 } 858 }, 859 // called when the user selects a list item from the dropdown 860 _selectListItem: function(listItem) { 861 var countryCodeAttr = this.isMobile ? "value" : "data-country-code"; 862 // update selected flag and active list item 863 this._selectFlag(listItem.attr(countryCodeAttr), true); 864 if (!this.isMobile) { 865 this._closeDropdown(); 866 } 867 this._updateDialCode(listItem.attr("data-dial-code"), true); 868 // 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. 869 this.telInput.trigger("change"); 870 // focus the input 871 this.telInput.focus(); 872 // 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 873 if (this.isGoodBrowser) { 874 var len = this.telInput.val().length; 875 this.telInput[0].setSelectionRange(len, len); 876 } 877 }, 878 // close the dropdown and unbind any listeners 879 _closeDropdown: function() { 880 this.countryList.addClass("hide"); 881 // update the arrow 882 this.selectedFlagInner.children(".arrow").removeClass("up"); 883 // unbind key events 884 $(document).off(this.ns); 885 // unbind click-off-to-close 886 $("html").off(this.ns); 887 // unbind hover and click listeners 888 this.countryList.off(this.ns); 889 }, 890 // check if an element is visible within it's container, else scroll until it is 891 _scrollTo: function(element, middle) { 892 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;
893 if (elementTop < containerTop) { 894 // scroll up 895 if (middle) { 896 newScrollTop -= middleOffset; 897 } 898 container.scrollTop(newScrollTop); 899 } else if (elementBottom > containerBottom) { 900 // scroll down 901 if (middle) { 902 newScrollTop += middleOffset; 903 } 904 var heightDifference = containerHeight - elementHeight; 905 container.scrollTop(newScrollTop - heightDifference); 906 } 907 }, 908 // replace any existing dial code with the new one (if not in nationalMode) 909 // 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 910 _updateDialCode: function(newDialCode, focusing) { 911 var inputVal = this.telInput.val(), newNumber; 912 // save having to pass this every time 913 newDialCode = "+" + newDialCode; 914 if (this.options.nationalMode && inputVal.charAt(0) != "+") { 915 // if nationalMode, we just want to re-format 916 newNumber = inputVal; 917 } else if (inputVal) { 918 // if the previous number contained a valid dial code, replace it 919 // (if more than just a plus character) 920 var prevDialCode = this._getDialCode(inputVal); 921 if (prevDialCode.length > 1) { 922 newNumber = inputVal.replace(prevDialCode, newDialCode); 923 } else { 924 // if the previous number didn't contain a dial code, we should persist it 925 var existingNumber = inputVal.charAt(0) != "+" ? $.trim(inputVal) : ""; 926 newNumber = newDialCode + existingNumber; 927 } 928 } else { 929 newNumber = !this.options.autoHideDialCode || focusing ? newDialCode : ""; 930 } 931 this._updateVal(newNumber, null, focusing); 932 }, 933 // try and extract a valid international dial code from a full telephone number 934 // Note: returns the raw string inc plus character and any whitespace/dots etc 935 _getDialCode: function(number) { 936 var dialCode = ""; 937 // only interested in international numbers (starting with a plus) 938 if (number.charAt(0) == "+") { 939 var numericChars = ""; 940 // iterate over chars 941 for (var i = 0; i < number.length; i++) { 942 var c = number.charAt(i); 943 // if char is number 944 if ($.isNumeric(c)) { 945 numericChars += c; 946 // if current numericChars make a valid dial code 947 if (this.countryCodes[numericChars]) { 948 // store the actual raw string (useful for matching later) 949 dialCode = number.substr(0, i + 1); 950 } 951 // longest dial code is 4 chars 952 if (numericChars.length == 4) { 953 break; 954 } 955 } 956 } 957 } 958 return dialCode; 959 }, 960 /******************** 961 * PUBLIC METHODS 962 ********************/ 963 // this is called when the geoip call returns 964 autoCountryLoaded: function() { 965 if (this.options.defaultCountry == "auto") { 966 this.options.defaultCountry = $.fn[pluginName].autoCountry; 967 this._setInitialState(); 968 this.autoCountryDeferred.resolve(); 969 } 970 }, 971 // remove plugin 972 destroy: function() { 973 if (!this.isMobile) { 974 // make sure the dropdown is closed (and unbind listeners) 975 this._closeDropdown(); 976 } 977 // key events, and focus/blur events if autoHideDialCode=true 978 this.telInput.off(this.ns); 979 if (this.isMobile) { 980 // change event on select country 981 this.countryList.off(this.ns); 982 } else { 983 // click event to open dropdown 984 this.selectedFlagInner.parent().off(this.ns); 985 // label click hack 986 this.telInput.closest("label").off(this.ns); 987 } 988 // remove markup 989 var container = this.telInput.parent(); 990 container.before(this.telInput).remove(); 991 }, 992 // extract the phone number extension if present 993 getExtension: function() { 994 return this.telInput.val().split(" ext. ")[1] || ""; 995 }, 996 // format the number to the given type 997 getNumber: function(type) { 998 if (window.intlTelInputUtils) { 999 return intlTelInputUtils.formatNumberByType(this.telInput.val(), this.selectedCountryData.iso2, type); 1000 } 1001 return ""; 1002 }, 1003 // get the type of the entered number e.g. landline/mobile 1004 getNumberType: function() { 1005 if (window.intlTelInputUtils) { 1006 return intlTelInputUtils.getNumberType(this.telInput.val(), this.selectedCountryData.iso2); 1007 } 1008 return -99; 1009 }, 1010 // get the country data for the currently selected flag 1011 getSelectedCountryData: function() { 1012 // if this is undefined, the plugin will return it's instance instead, so in that case an empty object makes more sense 1013 return this.selectedCountryData || {}; 1014 }, 1015 // get the validation error 1016 getValidationError: function() { 1017 if (window.intlTelInputUtils) { 1018 return intlTelInputUtils.getValidationError(this.telInput.val(), this.selectedCountryData.iso2); 1019 } 1020 return -99; 1021 }, 1022 // validate the input val - assumes the global function isValidNumber (from utilsScript) 1023 isValidNumber: function() { 1024 var val = $.trim(this.telInput.val()), countryCode = this.options.nationalMode ? this.selectedCountryData.iso2 : ""; 1025 if (window.intlTelInputUtils) { 1026 return intlTelInputUtils.isValidNumber(val, countryCode); 1027 } 1028 return false;
1029 }, 1030 // load the utils script 1031 loadUtils: function(path) { 1032 var that = this; 1033 var utilsScript = path || this.options.utilsScript; 1034 if (!$.fn[pluginName].loadedUtilsScript && utilsScript) { 1035 // 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) 1036 $.fn[pluginName].loadedUtilsScript = true; 1037 // dont use $.getScript as it prevents caching 1038 $.ajax({ 1039 url: utilsScript, 1040 success: function() { 1041 // tell all instances the utils are ready 1042 $(".intl-tel-input input").intlTelInput("utilsLoaded"); 1043 }, 1044 complete: function() { 1045 that.utilsScriptDeferred.resolve(); 1046 }, 1047 dataType: "script", 1048 cache: true 1049 }); 1050 } else { 1051 this.utilsScriptDeferred.resolve(); 1052 } 1053 }, 1054 // update the selected flag, and update the input val accordingly 1055 selectCountry: function(countryCode) { 1056 countryCode = countryCode.toLowerCase(); 1057 // check if already selected 1058 if (!this.selectedFlagInner.hasClass(countryCode)) { 1059 this._selectFlag(countryCode, true); 1060 this._updateDialCode(this.selectedCountryData.dialCode, false); 1061 } 1062 }, 1063 // set the input value and update the flag 1064 setNumber: function(number, format, addSuffix, preventConversion, isAllowedKey) { 1065 // ensure starts with plus 1066 if (!this.options.nationalMode && number.charAt(0) != "+") { 1067 number = "+" + number; 1068 } 1069 // we must update the flag first, which updates this.selectedCountryData, which is used later for formatting the number before displaying it 1070 this._updateFlagFromNumber(number); 1071 this._updateVal(number, format, addSuffix, preventConversion, isAllowedKey); 1072 }, 1073 // this is called when the utils are ready 1074 utilsLoaded: function() { 1075 // if autoFormat is enabled and there's an initial value in the input, then format it 1076 if (this.options.autoFormat && this.telInput.val()) { 1077 this._updateVal(this.telInput.val()); 1078 } 1079 this._updatePlaceholder(); 1080 } 1081 }; 1082 // adapted to allow public functions 1083 // using https://github.com/jquery-boilerplate/jquery-boilerplate/wiki/Extending-jQuery-Boilerplate 1084 $.fn[pluginName] = function(options) { 1085 var args = arguments; 1086 // Is the first parameter an object (options), or was omitted, 1087 // instantiate a new instance of the plugin. 1088 if (options === undefined || typeof options === "object") { 1089 var deferreds = []; 1090 this.each(function() { 1091 if (!$.data(this, "plugin_" + pluginName)) { 1092 var instance = new Plugin(this, options); 1093 var instanceDeferreds = instance._init(); 1094 // we now have 2 deffereds: 1 for auto country, 1 for utils script 1095 deferreds.push(instanceDeferreds[0]); 1096 deferreds.push(instanceDeferreds[1]); 1097 $.data(this, "plugin_" + pluginName, instance); 1098 } 1099 }); 1100 // return the promise from the "master" deferred object that tracks all the others 1101 return $.when.apply(null, deferreds); 1102 } else if (typeof options === "string" && options[0] !== "_") { 1103 // If the first parameter is a string and it doesn't start 1104 // with an underscore or "contains" the `init`-function, 1105 // treat this as a call to a public method. 1106 // Cache the method call to make it possible to return a value 1107 var returns; 1108 this.each(function() { 1109 var instance = $.data(this, "plugin_" + pluginName); 1110 // Tests that there's already a plugin-instance 1111 // and checks that the requested public method exists 1112 if (instance instanceof Plugin && typeof instance[options] === "function") { 1113 // Call the method of our plugin instance, 1114 // and pass it the supplied arguments. 1115 returns = instance[options].apply(instance, Array.prototype.slice.call(args, 1)); 1116 } 1117 // Allow instances to be destroyed via the 'destroy' method 1118 if (options === "destroy") { 1119 $.data(this, "plugin_" + pluginName, null); 1120 } 1121 }); 1122 // If the earlier cached method gives a value back return the value, 1123 // otherwise return this to preserve chainability. 1124 return returns !== undefined ? returns : this; 1125 } 1126 }; 1127 /******************** 1128 * STATIC METHODS 1129 ********************/ 1130 // get the country data object 1131 $.fn[pluginName].getCountryData = function() { 1132 return allCountries; 1133 }; 1134 $.fn[pluginName].version = "6.0.8"; 1135 // Tell JSHint to ignore this warning: "character may get silently deleted by one or more browsers"
1136 // jshint -W100 1137 // Array of country objects for the flag dropdown. 1138 // Each contains a name, country code (ISO 3166-1 alpha-2) and dial code. 1139 // Originally from https://github.com/mledoze/countries 1140 // then modified using the following JavaScript (NOW OUT OF DATE): 1141 /* 1142var result = []; 1143_.each(countries, function(c) { 1144 // ignore countries without a dial code 1145 if (c.callingCode[0].length) { 1146 result.push({ 1147 // var locals contains country names with localised versions in brackets 1148 n: _.findWhere(locals, { 1149 countryCode: c.cca2 1150 }).name, 1151 i: c.cca2.toLowerCase(), 1152 d: c.callingCode[0] 1153 }); 1154 } 1155}); 1156JSON.stringify(result); 1157*/ 1158 // then with a couple of manual re-arrangements to be alphabetical 1159 // then changed Kazakhstan from +76 to +7 1160 // and Vatican City from +379 to +39 (see issue 50) 1161 // and Caribean Netherlands from +5997 to +599 1162 // and Curacao from +5999 to +599 1163 // Removed: à land Islands, Christmas Island, Cocos Islands, Guernsey, Isle of Man, Jersey, Kosovo, Mayotte, Pitcairn Islands, South Georgia, Svalbard, Western Sahara 1164 // Update: converted objects to arrays to save bytes! 1165 // Update: added "priority" for countries with the same dialCode as others 1166 // Update: added array of area codes for countries with the same dialCode as others 1167 // So each country array has the following information: 1168 // [ 1169 // Country name, 1170 // iso2 code, 1171 // International dial code, 1172 // Order (if >1 country with same dial code), 1173 // Area codes (if >1 country with same dial code) 1174 // ] 1175 var allCountries = [ [ "Afghanistan (â«Ø§ÙØºØ§ÙØ³ØªØ§Ùâ¬â)", "af", "93" ], [ "Albania (Shqipëri)", "al", "355" ], [ "Algeria (â«Ø§Ùجزائرâ¬â)", "dz", "213" ], [ "American Samoa", "as", "1684" ], [ "Andorra", "ad", "376" ], [ "Angola", "ao", "244" ], [ "Anguilla", "ai", "1264" ], [ "Antigua and Barbuda", "ag", "1268" ], [ "Argentina", "ar", "54" ], [ "Armenia (ÕÕ¡ÕµÕ¡Õ½Õ¿Õ¡Õ¶)", "am", "374" ], [ "Aruba", "aw", "297" ], [ "Australia", "au", "61" ], [ "Austria (Ãsterreich)", "at", "43" ], [ "Azerbaijan (AzÉrbaycan)", "az", "994" ], [ "Bahamas", "bs", "1242" ], [ "Bahrain (â«Ø§ÙØ¨ØØ±ÙÙâ¬â)", "bh", "973" ], [ "Bangladesh (বাà¦à¦²à¦¾à¦¦à§à¦¶)", "bd", "880" ], [ "Barbados", "bb", "1246" ], [ "Belarus (ÐелаÑÑÑÑ)", "by", "375" ], [ "Belgium (België)", "be", "32" ], [ "Belize", "bz", "501" ], [ "Benin (Bénin)", "bj", "229" ], [ "Bermuda", "bm", "1441" ], [ "Bhutan (འà½à¾²à½´à½)", "bt", "975" ], [ "Bolivia", "bo", "591" ], [ "Bosnia and Herzegovina (ÐоÑна и ХеÑÑеговина)", "ba", "387" ], [ "Botswana", "bw", "267" ], [ "Brazil (Brasil)", "br", "55" ], [ "British Indian Ocean Territory", "io", "246" ], [ "British Virgin Islands", "vg", "1284" ], [ "Brunei", "bn", "673" ], [ "Bulgaria (ÐÑлгаÑиÑ)", "bg", "359" ], [ "Burkina Faso", "bf", "226" ], [ "Burundi (Uburundi)", "bi", "257" ], [ "Cambodia (ááááá»áá¶)", "kh", "855" ], [ "Cameroon (Cameroun)", "cm", "237" ], [ "Canada", "ca", "1", 1, [ "204", "226", "236", "249", "250", "289", "306", "343", "365", "387", "403", "416", "418", "431", "437", "438", "450", "506", "514", "519", "548", "579", "581", "587", "604", "613", "639", "647", "672", "705", "709", "742", "778", "780", "782", "807", "819", "825", "867", "873", "902", "905" ] ], [ "Cape Verde (Kabu Verdi)", "cv", "238" ], [ "Caribbean Netherlands", "bq", "599", 1 ], [ "Cayman Islands", "ky", "1345" ], [ "Central African Republic (République centrafricaine)", "cf", "236" ], [ "Chad (Tchad)", "td", "235" ], [ "Chile", "cl", "56" ], [ "China (ä¸å½)", "cn", "86" ], [ "Colombia", "co", "57" ], [ "Comoros (â«Ø¬Ø²Ø± اÙÙ٠رâ¬â)", "km", "269" ], [ "Congo (DRC) (Jamhuri ya Kidemokrasia ya Kongo)", "cd", "243" ], [ "Congo (Republic) (Congo-Brazzaville)", "cg", "242" ], [ "Cook Islands", "ck", "682" ], [ "Costa Rica", "cr", "506" ], [ "Côte dâIvoire", "ci", "225" ], [ "Croatia (Hrvatska)", "hr", "385" ], [ "Cuba", "cu", "53" ], [ "Curaçao", "cw", "599", 0 ], [ "Cyprus (ÎÏÏÏοÏ)", "cy", "357" ], [ "Czech Republic (Äeská republika)", "cz", "420" ], [ "Denmark (Danmark)", "dk", "45" ], [ "Djibouti", "dj", "253" ], [ "Dominica", "dm", "1767" ], [ "Dominican Republic (República Dominicana)", "do", "1", 2, [ "809", "829", "849" ] ], [ "Ecuador", "ec", "593" ], [ "Egypt (â«Ù صرâ¬â)", "eg", "20" ], [ "El Salvador", "sv", "503" ], [ "Equatorial Guinea (Guinea Ecuatorial)", "gq", "240" ], [ "Eritrea", "er", "291" ], [ "Estonia (Eesti)", "ee", "372" ], [ "Ethiopia", "et", "251" ], [ "Falkland Islands (Islas Malvinas)", "fk", "500" ], [ "Faroe Islands (Føroyar)", "fo", "298" ], [ "Fiji", "fj", "679" ], [ "Finland (Suomi)", "fi", "358" ], [ "France", "fr", "33" ], [ "French Guiana (Guyane française)", "gf", "594" ], [ "French Polynesia (Polynésie française)", "pf", "689" ], [ "Gabon", "ga", "241" ], [ "Gambia", "gm", "220" ], [ "Georgia (á¡áá¥áá ááááá)", "ge", "995" ], [ "Germany (Deutschland)", "de", "49" ], [ "Ghana (Gaana)", "gh", "233" ], [ "Gibraltar", "gi", "350" ], [ "Greece (Îλλάδα)", "gr", "30" ], [ "Greenland (Kalaallit Nun
1175aat)", "gl", "299" ], [ "Grenada", "gd", "1473" ], [ "Guadeloupe", "gp", "590", 0 ], [ "Guam", "gu", "1671" ], [ "Guatemala", "gt", "502" ], [ "Guinea (Guinée)", "gn", "224" ], [ "Guinea-Bissau (Guiné Bissau)", "gw", "245" ], [ "Guyana", "gy", "592" ], [ "Haiti", "ht", "509" ], [ "Honduras", "hn", "504" ], [ "Hong Kong (馿¸¯)", "hk", "852" ], [ "Hungary (Magyarország)", "hu", "36" ], [ "Iceland (Ãsland)", "is", "354" ], [ "India (à¤à¤¾à¤°à¤¤)", "in", "91" ], [ "Indonesia", "id", "62" ], [ "Iran (â«Ø§ÛراÙâ¬â)", "ir", "98" ], [ "Iraq (â«Ø§ÙعراÙâ¬â)", "iq", "964" ], [ "Ireland", "ie", "353" ], [ "Israel (â«×שר××â¬â)", "il", "972" ], [ "Italy (Italia)", "it", "39", 0 ], [ "Jamaica", "jm", "1876" ], [ "Japan (æ¥æ¬)", "jp", "81" ], [ "Jordan (â«Ø§ÙأردÙâ¬â)", "jo", "962" ], [ "Kazakhstan (ÐÐ°Ð·Ð°Ñ ÑÑан)", "kz", "7", 1 ], [ "Kenya", "ke", "254" ], [ "Kiribati", "ki", "686" ], [ "Kuwait (â«Ø§ÙÙÙÙØªâ¬â)", "kw", "965" ], [ "Kyrgyzstan (ÐÑÑгÑзÑÑан)", "kg", "996" ], [ "Laos (ລາວ)", "la", "856" ], [ "Latvia (Latvija)", "lv", "371" ], [ "Lebanon (â«ÙØ¨ÙØ§Ùâ¬â)", "lb", "961" ], [ "Lesotho", "ls", "266" ], [ "Liberia", "lr", "231" ], [ "Libya (â«ÙÙØ¨Ùاâ¬â)", "ly", "218" ], [ "Liechtenstein", "li", "423" ], [ "Lithuania (Lietuva)", "lt", "370" ], [ "Luxembourg", "lu", "352" ], [ "Macau (æ¾³é)", "mo", "853" ], [ "Macedonia (FYROM) (ÐакедониÑа)", "mk", "389" ], [ "Madagascar (Madagasikara)", "mg", "261" ], [ "Malawi", "mw", "265" ], [ "Malaysia", "my", "60" ], [ "Maldives", "mv", "960" ], [ "Mali", "ml", "223" ], [ "Malta", "mt", "356" ], [ "Marshall Islands", "mh", "692" ], [ "Martinique", "mq", "596" ], [ "Mauritania (â«Ù ÙØ±ÙتاÙÙØ§â¬â)", "mr", "222" ], [ "Mauritius (Moris)", "mu", "230" ], [ "Mexico (México)", "mx", "52" ], [ "Micronesia", "fm", "691" ], [ "Moldova (Republica Moldova)", "md", "373" ], [ "Monaco", "mc", "377" ], [ "Mongolia (Ðонгол)", "mn", "976" ], [ "Montenegro (Crna Gora)", "me", "382" ], [ "Montserrat", "ms", "1664" ], [ "Morocco (â«Ø§Ù٠غربâ¬â)", "ma", "212" ], [ "Mozambique (Moçambique)", "mz", "258" ], [ "Myanmar (Burma) (áá¼ááºáá¬)", "mm", "95" ], [ "Namibia (Namibië)", "na", "264" ], [ "Nauru", "nr", "674" ], [ "Nepal (नà¥à¤ªà¤¾à¤²)", "np", "977" ], [ "Netherlands (Nederland)", "nl", "31" ], [ "New Caledonia (Nouvelle-Calédonie)", "nc", "687" ], [ "New Zealand", "nz", "64" ], [ "Nicaragua", "ni", "505" ], [ "Niger (Nijar)", "ne", "227" ], [ "Nigeria", "ng", "234" ], [ "Niue", "nu", "683" ], [ "Norfolk Island", "nf", "672" ], [ "North Korea (ì¡°ì 민주주ì ì¸ë¯¼ ê³µíêµ)", "kp", "850" ], [ "Northern Mariana Islands", "mp", "1670" ], [ "Norway (Norge)", "no", "47" ], [ "Oman (â«Ø¹Ù٠اÙâ¬â)", "om", "968" ], [ "Pakistan (â«Ù¾Ø§Ú©Ø³ØªØ§Ùâ¬â)", "pk", "92" ], [ "Palau", "pw", "680" ], [ "Palestine (â«ÙÙØ³Ø·ÙÙâ¬â)", "ps", "970" ], [ "Panama (Panamá)", "pa", "507" ], [ "Papua New Guinea", "pg", "675" ], [ "Paraguay", "py", "595" ], [ "Peru (Perú)", "pe", "51" ], [ "Philippines", "ph", "63" ], [ "Poland (Polska)", "pl", "48" ], [ "Portugal", "pt", "351" ], [ "Puerto Rico", "pr", "1", 3, [ "787", "939" ] ], [ "Qatar (â«Ùطرâ¬â)", "qa", "974" ], [ "Réunion (La Réunion)", "re", "262" ], [ "Romania (România)", "ro", "40" ], [ "Russia (РоÑÑиÑ)", "ru", "7", 0 ], [ "Rwanda", "rw", "250" ], [ "Saint Barthélemy (Saint-Barthélemy)", "bl", "590", 1 ], [ "Saint Helena", "sh", "290" ], [ "Saint Kitts and Nevis", "kn", "1869" ], [ "Saint Lucia", "lc", "1758" ], [ "Saint Martin (Saint-Martin (partie française))", "mf", "590", 2 ], [ "Saint Pierre and Miquelon (Saint-Pierre-et-Miquelon)", "pm", "508" ], [ "Saint Vincent and the Grenadines", "vc", "1784" ], [ "Samoa", "ws", "685" ], [ "San Marino", "sm", "378" ], [ "São Tomé and PrÃncipe (São Tomé e PrÃncipe)", "st", "239" ], [ "Saudi Arabia (â«Ø§ÙÙ Ù ÙÙØ© Ø§ÙØ¹Ø±Ø¨ÙØ© Ø§ÙØ³Ø¹ÙØ¯ÙØ©â¬â)", "sa", "966" ], [ "Senegal (Sénégal)", "sn", "221" ], [ "Serbia (СÑбиÑа)", "rs", "381" ], [ "Seychelles", "sc", "248" ], [ "Sierra Leone", "sl", "232" ], [ "Singapore", "sg", "65" ], [ "Sint Maarten", "sx", "1721" ], [ "Slovakia (Slovensko)", "sk", "421" ], [ "Slovenia (Slovenija)", "si", "386" ], [ "Solomon Islands", "sb", "677" ], [ "Somalia (Soomaaliya)", "so", "252" ], [ "South Africa", "za", "27" ], [ "South Korea (ëí민êµ)", "kr", "82" ], [ "South Sudan (â«Ø¬ÙÙØ¨ Ø§ÙØ³ÙداÙâ¬â)", "ss", "211" ], [ "Spain (España)", "es", "34" ], [ "Sri Lanka (à·à·âර෠ලà¶à¶à·à·)", "lk", "94" ], [ "Sudan (â«Ø§ÙØ³ÙØ¯Ø§Ùâ¬â)", "sd", "249" ], [ "Suriname", "sr", "597" ], [ "Swaziland", "sz", "268" ], [ "Sweden (Sverige)", "se", "46" ], [ "Switzerland (Schweiz)", "ch", "41" ], [ "Syria (â«Ø³ÙØ±ÙØ§â¬â)", "sy", "963" ], [ "Taiwan (å°ç£)", "tw", "886" ], [ "Tajikistan", "tj", "992" ], [ "Tanzania", "tz", "255" ], [ "Thailand (à¹à¸à¸¢)", "th", "66" ], [ "Timor-Leste", "tl", "670" ], [ "Togo", "tg", "228" ], [ "Tokelau", "tk", "690" ], [ "Tonga", "to", "676" ], [ "Trinidad and Tobago", "tt", "1868" ], [ "Tunisia (â«ØªÙÙØ³â¬â)", "tn", "216" ], [ "Turkey (Türkiye)", "tr", "90" ], [ "Turkmenistan", "tm", "993" ], [ "Turks and Caicos Islands", "tc", "1649" ], [ "Tuvalu", "tv", "688" ], [ "U.S. Virgin Islands", "vi", "1340" ], [ "Uganda", "ug", "256" ], [ "Ukraine (УкÑаÑна)", "ua", "380" ], [ "United Arab Emirates (â«Ø§Ùإ٠ارات Ø§ÙØ¹Ø±Ø¨ÙØ© اÙÙ ØªØØ¯Ø©â¬â)", "ae", "971" ], [ "United Kingdom", "gb", "44" ], [ "United States", "us", "1", 0 ], [ "Uruguay", "uy", "598" ], [ "Uzbekistan (OÊ»zbekiston)", "uz", "998" ], [ "Vanuatu", "vu", "678" ], [ "Vatican City (Città del Vaticano)", "va", "39", 1 ], [ "Venezuela", "ve", "58" ], [ "Vietnam (Viá»t Nam)", "vn", "84" ], [ "Wallis and Futuna", "wf", "681" ], [ "Yemen (â«Ø§ÙÙÙ Ùâ¬â)", "ye", "967" ], [ "Zambia", "zm", "260" ], [ "Zimbabwe", "zw", "263" ] ]; 1176 // loop over all of the countries above 1177 for (var i = 0; i < allCountries.length; i++) { 1178 var c = allCountries[i]; 1179 allCountries[i] = { 1180 name: c[0], 1181 iso2: c[1], 1182 dialCode: c[2], 1183 priority: c[3] || 0, 1184 areaCodes: c[4] || null 1185 }; 1186 } 1187});
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.