", {
163 | "class": "selected-flag"
164 | }).appendTo(flagsContainer);
165 | this.selectedFlagInner = $("
", {
166 | "class": "flag"
167 | }).appendTo(selectedFlag);
168 | // CSS triangle
169 | $("
", {
170 | "class": "arrow"
171 | }).appendTo(this.selectedFlagInner);
172 | // country list contains: preferred countries, then divider, then all countries
173 | this.countryList = $("
", {
174 | "class": "country-list v-hide"
175 | }).appendTo(flagsContainer);
176 | if (this.preferredCountries.length) {
177 | this._appendListItems(this.preferredCountries, "preferred");
178 | $("- ", {
179 | "class": "divider"
180 | }).appendTo(this.countryList);
181 | }
182 | this._appendListItems(this.countries, "");
183 | // now we can grab the dropdown height, and hide it properly
184 | this.dropdownHeight = this.countryList.outerHeight();
185 | this.countryList.removeClass("v-hide").addClass("hide");
186 | // and set the width
187 | if (this.options.responsiveDropdown) {
188 | this.countryList.outerWidth(this.telInput.outerWidth());
189 | }
190 | // this is useful in lots of places
191 | this.countryListItems = this.countryList.children(".country");
192 | },
193 | // add a country
- to the countryList
container
194 | _appendListItems: function(countries, className) {
195 | // we create so many DOM elements, I decided it was faster to build a temp string
196 | // and then add everything to the DOM in one go at the end
197 | var tmp = "";
198 | // for each country
199 | for (var i = 0; i < countries.length; i++) {
200 | var c = countries[i];
201 | // open the list item
202 | tmp += "- ";
203 | // add the flag
204 | tmp += "";
205 | // and the country name and dial code
206 | tmp += "" + c.name + "";
207 | tmp += "+" + c.dialCode + "";
208 | // close the list item
209 | tmp += "
";
210 | }
211 | this.countryList.append(tmp);
212 | },
213 | // set the initial state of the input value and the selected flag
214 | _setInitialState: function() {
215 | var val = this.telInput.val();
216 | // if the input is not pre-populated, or if it doesn't contain a valid dial code, fall back to the default country
217 | // Note: calling setNumber will also format the number
218 | if (!val || !this.setNumber(val)) {
219 | // flag is not set, so set to the default country
220 | var defaultCountry;
221 | // check the defaultCountry option, else fall back to the first in the list
222 | if (this.options.defaultCountry) {
223 | defaultCountry = this._getCountryData(this.options.defaultCountry, false, false);
224 | } else {
225 | defaultCountry = this.preferredCountries.length ? this.preferredCountries[0] : this.countries[0];
226 | }
227 | this._selectFlag(defaultCountry.iso2);
228 | // if autoHideDialCode is disabled, insert the default dial code
229 | if (!val && !this.options.autoHideDialCode) {
230 | this._resetToDialCode(defaultCountry.dialCode);
231 | }
232 | }
233 | },
234 | // initialise the main event listeners: input keydown, and click selected flag
235 | _initListeners: function() {
236 | var that = this;
237 | // auto hide dial code option
238 | if (this.options.autoHideDialCode) {
239 | this._initAutoHideDialCode();
240 | }
241 | // 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
242 | var label = this.telInput.closest("label");
243 | if (label.length) {
244 | label.on("click" + this.ns, function(e) {
245 | // if the dropdown is closed, then focus the input, else ignore the click
246 | if (that.countryList.hasClass("hide")) {
247 | that.telInput.focus();
248 | } else {
249 | e.preventDefault();
250 | }
251 | });
252 | }
253 | if (this.options.autoFormat) {
254 | // format number and update flag on keypress
255 | // use keypress event as we want to ignore all input except for a select few keys,
256 | // but we dont want to ignore the navigation keys like the arrows etc.
257 | // 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...
258 | this.telInput.on("keypress" + this.ns, function(e) {
259 | // 32 is space, and after that it's all chars (not meta/nav keys)
260 | // this fix is needed for Firefox, which triggers keypress event for some meta/nav keys
261 | if (e.which >= keys.SPACE) {
262 | e.preventDefault();
263 | // allowed keys are now just numeric keys
264 | var isAllowed = e.which >= keys.ZERO && e.which <= keys.NINE, input = that.telInput[0], noSelection = that.isGoodBrowser && input.selectionStart == input.selectionEnd;
265 | // 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
266 | if (isAllowed || noSelection) {
267 | var newChar = isAllowed ? String.fromCharCode(e.which) : null;
268 | that._handleInputKey(newChar, true);
269 | }
270 | }
271 | });
272 | }
273 | // handle keyup event
274 | // for autoFormat: we use keyup to catch delete events after the fact
275 | this.telInput.on("keyup" + this.ns, function(e) {
276 | if (that.options.autoFormat) {
277 | var isCtrl = e.which == keys.CTRL || e.which == keys.CMD1 || e.which == keys.CMD2, input = that.telInput[0], noSelection = that.isGoodBrowser && input.selectionStart == input.selectionEnd, cursorAtEnd = that.isGoodBrowser && input.selectionStart == that.telInput.val().length;
278 | // if delete: format with suffix
279 | // if backspace: format (if cursorAtEnd: no suffix)
280 | // if ctrl and no selection (i.e. could be paste): format with suffix
281 | if (e.which == keys.DEL || e.which == keys.BSPACE || isCtrl && noSelection) {
282 | var addSuffix = !(e.which == keys.BSPACE && cursorAtEnd);
283 | that._handleInputKey(null, addSuffix);
284 | }
285 | // prevent deleting the plus
286 | var val = that.telInput.val();
287 | if (val.substr(0, 1) != "+") {
288 | // newCursorPos is current pos + 1 to account for the plus we are about to add
289 | var newCursorPos = that.isGoodBrowser ? input.selectionStart + 1 : 0;
290 | that.telInput.val("+" + val);
291 | if (that.isGoodBrowser) {
292 | input.setSelectionRange(newCursorPos, newCursorPos);
293 | }
294 | }
295 | } else {
296 | // if no autoFormat, just update flag
297 | that._updateFlag();
298 | }
299 | });
300 | // toggle country dropdown on click
301 | var selectedFlag = this.selectedFlagInner.parent();
302 | selectedFlag.on("click" + this.ns, function(e) {
303 | // only intercept this event if we're opening the dropdown
304 | // else let it bubble up to the top ("click-off-to-close" listener)
305 | // we cannot just stopPropagation as it may be needed to close another instance
306 | if (that.countryList.hasClass("hide") && !that.telInput.prop("disabled")) {
307 | that._showDropdown();
308 | }
309 | });
310 | // if the user has specified the path to the utils script
311 | // inject a new script element for it at the end of the body
312 | if (this.options.utilsScript && !$.fn[pluginName].injectedUtilsScript) {
313 | // don't do this twice!
314 | $.fn[pluginName].injectedUtilsScript = true;
315 | var injectUtilsScript = function() {
316 | $.getScript(that.options.utilsScript, function() {
317 | // tell all instances the utils are ready
318 | $(".intl-tel-input input").intlTelInput("utilsLoaded");
319 | });
320 | };
321 | // if the plugin is being initialised after the window.load event has already been fired
322 | if (windowLoaded) {
323 | injectUtilsScript();
324 | } else {
325 | // wait until the load event so we don't block any other requests e.g. the flags image
326 | $(window).load(injectUtilsScript);
327 | }
328 | }
329 | },
330 | // when autoFormat is enabled: handle various key events on the input: the 2 main situations are 1) adding a new number character, which will replace any selection, reformat, and try to preserve the cursor position. and 2) reformatting on backspace, or paste event
331 | _handleInputKey: function(newNumericChar, addSuffix) {
332 | var val = this.telInput.val(), newCursor = null, cursorAtEnd = false, // raw DOM element
333 | input = this.telInput[0];
334 | if (this.isGoodBrowser) {
335 | var selectionEnd = input.selectionEnd, originalLen = val.length;
336 | cursorAtEnd = selectionEnd == originalLen;
337 | // if handling a new number character: insert it in the right place and calculate the new cursor position
338 | if (newNumericChar) {
339 | // replace any selection they may have made with the new char
340 | val = val.substring(0, input.selectionStart) + newNumericChar + val.substring(selectionEnd, originalLen);
341 | // if the cursor was not at the end then calculate it's new pos
342 | if (!cursorAtEnd) {
343 | newCursor = selectionEnd + (val.length - originalLen);
344 | }
345 | } else {
346 | // here we're not handling a new char, we're just doing a re-format, but we still need to maintain the cursor position
347 | newCursor = input.selectionStart;
348 | }
349 | } else if (newNumericChar) {
350 | val += newNumericChar;
351 | }
352 | // update the number and flag
353 | this.setNumber(val, addSuffix);
354 | // update the cursor position
355 | if (this.isGoodBrowser) {
356 | // if it was at the end, keep it there
357 | if (cursorAtEnd) {
358 | newCursor = this.telInput.val().length;
359 | }
360 | input.setSelectionRange(newCursor, newCursor);
361 | }
362 | },
363 | // on focus: if empty add dial code. on blur: if just dial code, then empty it
364 | _initAutoHideDialCode: function() {
365 | var that = this;
366 | // mousedown decides where the cursor goes, so if we're focusing
367 | // we must preventDefault as we'll be inserting the dial code,
368 | // and we want the cursor to be at the end no matter where they click
369 | this.telInput.on("mousedown" + this.ns, function(e) {
370 | if (!that.telInput.is(":focus") && !that.telInput.val()) {
371 | e.preventDefault();
372 | // but this also cancels the focus, so we must trigger that manually
373 | that.telInput.focus();
374 | }
375 | });
376 | // on focus: if empty, insert the dial code for the currently selected flag
377 | this.telInput.on("focus" + this.ns, function() {
378 | if (!that.telInput.val()) {
379 | that._updateVal("+" + that.selectedCountryData.dialCode, true);
380 | // after auto-inserting a dial code, if the first key they hit is '+' then assume
381 | // they are entering a new number, so remove the dial code.
382 | // use keypress instead of keydown because keydown gets triggered for the shift key
383 | // (required to hit the + key), and instead of keyup because that shows the new '+'
384 | // before removing the old one
385 | that.telInput.one("keypress.plus" + that.ns, function(e) {
386 | if (e.which == keys.PLUS) {
387 | that.telInput.val("+");
388 | }
389 | });
390 | // after tabbing in, make sure the cursor is at the end
391 | // we must use setTimeout to get outside of the focus handler as it seems the
392 | // selection happens after that
393 | setTimeout(function() {
394 | that._cursorToEnd();
395 | });
396 | }
397 | });
398 | // on blur: if just a dial code then remove it
399 | this.telInput.on("blur" + this.ns, function() {
400 | var value = that.telInput.val(), startsPlus = value.substr(0, 1) == "+";
401 | if (startsPlus) {
402 | var numeric = value.replace(/\D/g, ""), clean = "+" + numeric;
403 | // if just a plus, or if just a dial code
404 | if (!numeric || that.selectedCountryData.dialCode == numeric) {
405 | that.telInput.val("");
406 | }
407 | }
408 | // remove the keypress listener we added on focus
409 | that.telInput.off("keypress.plus" + that.ns);
410 | });
411 | },
412 | // put the cursor to the end of the input (usually after a focus event)
413 | _cursorToEnd: function() {
414 | var input = this.telInput[0];
415 | if (this.isGoodBrowser) {
416 | var len = this.telInput.val().length;
417 | input.setSelectionRange(len, len);
418 | }
419 | },
420 | // show the dropdown
421 | _showDropdown: function() {
422 | this._setDropdownPosition();
423 | // update highlighting and scroll to active list item
424 | var activeListItem = this.countryList.children(".active");
425 | this._highlightListItem(activeListItem);
426 | // show it
427 | this.countryList.removeClass("hide");
428 | this._scrollTo(activeListItem);
429 | // bind all the dropdown-related listeners: mouseover, click, click-off, keydown
430 | this._bindDropdownListeners();
431 | // update the arrow
432 | this.selectedFlagInner.children(".arrow").addClass("up");
433 | },
434 | // decide where to position dropdown (depends on position within viewport, and scroll)
435 | _setDropdownPosition: function() {
436 | var inputTop = this.telInput.offset().top, windowTop = $(window).scrollTop(), // dropdownFitsBelow = (dropdownBottom < windowBottom)
437 | dropdownFitsBelow = inputTop + this.telInput.outerHeight() + this.dropdownHeight < windowTop + $(window).height(), dropdownFitsAbove = inputTop - this.dropdownHeight > windowTop;
438 | // dropdownHeight - 1 for border
439 | var cssTop = !dropdownFitsBelow && dropdownFitsAbove ? "-" + (this.dropdownHeight - 1) + "px" : "";
440 | this.countryList.css("top", cssTop);
441 | },
442 | // we only bind dropdown listeners when the dropdown is open
443 | _bindDropdownListeners: function() {
444 | var that = this;
445 | // when mouse over a list item, just highlight that one
446 | // we add the class "highlight", so if they hit "enter" we know which one to select
447 | this.countryList.on("mouseover" + this.ns, ".country", function(e) {
448 | that._highlightListItem($(this));
449 | });
450 | // listen for country selection
451 | this.countryList.on("click" + this.ns, ".country", function(e) {
452 | that._selectListItem($(this));
453 | });
454 | // click off to close
455 | // (except when this initial opening click is bubbling up)
456 | // we cannot just stopPropagation as it may be needed to close another instance
457 | var isOpening = true;
458 | $("html").on("click" + this.ns, function(e) {
459 | if (!isOpening) {
460 | that._closeDropdown();
461 | }
462 | isOpening = false;
463 | });
464 | // listen for up/down scrolling, enter to select, or letters to jump to country name.
465 | // use keydown as keypress doesn't fire for non-char keys and we want to catch if they
466 | // just hit down and hold it to scroll down (no keyup event).
467 | // listen on the document because that's where key events are triggered if no input has focus
468 | var query = "", queryTimer = null;
469 | $(document).on("keydown" + this.ns, function(e) {
470 | // prevent down key from scrolling the whole page,
471 | // and enter key from submitting a form etc
472 | e.preventDefault();
473 | if (e.which == keys.UP || e.which == keys.DOWN) {
474 | // up and down to navigate
475 | that._handleUpDownKey(e.which);
476 | } else if (e.which == keys.ENTER) {
477 | // enter to select
478 | that._handleEnterKey();
479 | } else if (e.which == keys.ESC) {
480 | // esc to close
481 | that._closeDropdown();
482 | } else if (e.which >= keys.A && e.which <= keys.Z || e.which == keys.SPACE) {
483 | // upper case letters (note: keyup/keydown only return upper case letters)
484 | // jump to countries that start with the query string
485 | if (queryTimer) {
486 | clearTimeout(queryTimer);
487 | }
488 | query += String.fromCharCode(e.which);
489 | that._searchForCountry(query);
490 | // if the timer hits 1 second, reset the query
491 | queryTimer = setTimeout(function() {
492 | query = "";
493 | }, 1e3);
494 | }
495 | });
496 | },
497 | // highlight the next/prev item in the list (and ensure it is visible)
498 | _handleUpDownKey: function(key) {
499 | var current = this.countryList.children(".highlight").first();
500 | var next = key == keys.UP ? current.prev() : current.next();
501 | if (next.length) {
502 | // skip the divider
503 | if (next.hasClass("divider")) {
504 | next = key == keys.UP ? next.prev() : next.next();
505 | }
506 | this._highlightListItem(next);
507 | this._scrollTo(next);
508 | }
509 | },
510 | // select the currently highlighted item
511 | _handleEnterKey: function() {
512 | var currentCountry = this.countryList.children(".highlight").first();
513 | if (currentCountry.length) {
514 | this._selectListItem(currentCountry);
515 | }
516 | },
517 | // find the first list item whose name starts with the query string
518 | _searchForCountry: function(query) {
519 | for (var i = 0; i < this.countries.length; i++) {
520 | if (this._startsWith(this.countries[i].name, query)) {
521 | var listItem = this.countryList.children("[data-country-code=" + this.countries[i].iso2 + "]").not(".preferred");
522 | // update highlighting and scroll
523 | this._highlightListItem(listItem);
524 | this._scrollTo(listItem, true);
525 | break;
526 | }
527 | }
528 | },
529 | // check if (uppercase) string a starts with string b
530 | _startsWith: function(a, b) {
531 | return a.substr(0, b.length).toUpperCase() == b;
532 | },
533 | // update the input's value to the given val
534 | // if autoFormat=true, format it first according to the country-specific formatting rules
535 | _updateVal: function(val, addSuffix) {
536 | var formatted;
537 | if (this.options.autoFormat && window.intlTelInputUtils) {
538 | // don't try to add the suffix if we dont have a full dial code
539 | if (!this._getDialCode(val)) {
540 | addSuffix = false;
541 | }
542 | formatted = intlTelInputUtils.formatNumber(val, addSuffix);
543 | } else {
544 | // no autoFormat, so just insert the original value
545 | formatted = val;
546 | }
547 | this.telInput.val(formatted);
548 | },
549 | // update the selected flag
550 | _updateFlag: function(number) {
551 | // try and extract valid dial code from input
552 | var dialCode = this._getDialCode(number);
553 | if (dialCode) {
554 | // check if one of the matching countries is already selected
555 | var countryCodes = this.countryCodes[dialCode.replace(/\D/g, "")], alreadySelected = false;
556 | // countries with area codes: we must always update the flag as if it's not an exact match
557 | // we should always default to the first country in the list. This is to avoid having to
558 | // explicitly define every possible area code in America (there are 999 possible area codes)
559 | if (!this.selectedCountryData || !this.selectedCountryData.hasAreaCodes) {
560 | for (var i = 0; i < countryCodes.length; i++) {
561 | if (this.selectedFlagInner.hasClass(countryCodes[i])) {
562 | alreadySelected = true;
563 | }
564 | }
565 | }
566 | // else choose the first in the list
567 | if (!alreadySelected) {
568 | this._selectFlag(countryCodes[0]);
569 | }
570 | }
571 | return dialCode;
572 | },
573 | // reset the input value to just a dial code
574 | _resetToDialCode: function(dialCode) {
575 | // if nationalMode is enabled then don't insert the dial code
576 | var value = this.options.nationalMode ? "" : "+" + dialCode;
577 | this.telInput.val(value);
578 | },
579 | // remove highlighting from other list items and highlight the given item
580 | _highlightListItem: function(listItem) {
581 | this.countryListItems.removeClass("highlight");
582 | listItem.addClass("highlight");
583 | },
584 | // find the country data for the given country code
585 | // the ignoreOnlyCountriesOption is only used during init() while parsing the onlyCountries array
586 | _getCountryData: function(countryCode, ignoreOnlyCountriesOption, allowFail) {
587 | var countryList = ignoreOnlyCountriesOption ? allCountries : this.countries;
588 | for (var i = 0; i < countryList.length; i++) {
589 | if (countryList[i].iso2 == countryCode) {
590 | return countryList[i];
591 | }
592 | }
593 | if (allowFail) {
594 | return null;
595 | } else {
596 | throw new Error("No country data for '" + countryCode + "'");
597 | }
598 | },
599 | // update the selected flag and the active list item
600 | _selectFlag: function(countryCode) {
601 | this.selectedFlagInner.attr("class", "flag " + countryCode);
602 | // update the placeholder
603 | if (window.intlTelInputUtils) {
604 | this.telInput.attr("placeholder", intlTelInputUtils.getExampleNumber(countryCode));
605 | }
606 | // update the title attribute
607 | this.selectedCountryData = this._getCountryData(countryCode, false, false);
608 | var title = this.selectedCountryData.name + ": +" + this.selectedCountryData.dialCode;
609 | this.selectedFlagInner.parent().attr("title", title);
610 | // update the active list item
611 | var listItem = this.countryListItems.children(".flag." + countryCode).first().parent();
612 | this.countryListItems.removeClass("active");
613 | listItem.addClass("active");
614 | },
615 | // called when the user selects a list item from the dropdown
616 | _selectListItem: function(listItem) {
617 | // update selected flag and active list item
618 | var countryCode = listItem.attr("data-country-code");
619 | this._selectFlag(countryCode);
620 | this._closeDropdown();
621 | // update input value
622 | if (!this.options.nationalMode) {
623 | this._updateDialCode("+" + listItem.attr("data-dial-code"));
624 | }
625 | // always fire the change event as even if nationalMode=true (and we haven't updated
626 | // the input val), the system as a whole has still changed - see country-sync example
627 | this.telInput.trigger("change");
628 | // focus the input
629 | this.telInput.focus();
630 | this._cursorToEnd();
631 | },
632 | // close the dropdown and unbind any listeners
633 | _closeDropdown: function() {
634 | this.countryList.addClass("hide");
635 | // update the arrow
636 | this.selectedFlagInner.children(".arrow").removeClass("up");
637 | // unbind key events
638 | $(document).off(this.ns);
639 | // unbind click-off-to-close
640 | $("html").off(this.ns);
641 | // unbind hover and click listeners
642 | this.countryList.off(this.ns);
643 | },
644 | // check if an element is visible within it's container, else scroll until it is
645 | _scrollTo: function(element, middle) {
646 | 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;
647 | if (elementTop < containerTop) {
648 | // scroll up
649 | if (middle) {
650 | newScrollTop -= middleOffset;
651 | }
652 | container.scrollTop(newScrollTop);
653 | } else if (elementBottom > containerBottom) {
654 | // scroll down
655 | if (middle) {
656 | newScrollTop += middleOffset;
657 | }
658 | var heightDifference = containerHeight - elementHeight;
659 | container.scrollTop(newScrollTop - heightDifference);
660 | }
661 | },
662 | // replace any existing dial code with the new one
663 | // currently this is only called from _selectListItem
664 | _updateDialCode: function(newDialCode) {
665 | var inputVal = this.telInput.val(), prevDialCode = this._getDialCode(), newNumber;
666 | // if the previous number contained a valid dial code, replace it
667 | // (if more than just a plus character)
668 | if (prevDialCode.length > 1) {
669 | newNumber = inputVal.replace(prevDialCode, newDialCode);
670 | } else {
671 | // if the previous number didn't contain a dial code, we should persist it
672 | var existingNumber = inputVal && inputVal.substr(0, 1) != "+" ? $.trim(inputVal) : "";
673 | newNumber = newDialCode + existingNumber;
674 | }
675 | this._updateVal(newNumber, true);
676 | },
677 | // try and extract a valid international dial code from a full telephone number
678 | // Note: returns the raw string inc plus character and any whitespace/dots etc
679 | _getDialCode: function(number) {
680 | var dialCode = "", inputVal = number || this.telInput.val();
681 | // only interested in international numbers (starting with a plus)
682 | if (inputVal.charAt(0) == "+") {
683 | var numericChars = "";
684 | // iterate over chars
685 | for (var i = 0; i < inputVal.length; i++) {
686 | var c = inputVal.charAt(i);
687 | // if char is number
688 | if ($.isNumeric(c)) {
689 | numericChars += c;
690 | // if current numericChars make a valid dial code
691 | if (this.countryCodes[numericChars]) {
692 | // store the actual raw string (useful for matching later)
693 | dialCode = inputVal.substring(0, i + 1);
694 | }
695 | // longest dial code is 4 chars
696 | if (numericChars.length == 4) {
697 | break;
698 | }
699 | }
700 | }
701 | }
702 | return dialCode;
703 | },
704 | /********************
705 | * PUBLIC METHODS
706 | ********************/
707 | // remove plugin
708 | destroy: function() {
709 | // make sure the dropdown is closed (and unbind listeners)
710 | this._closeDropdown();
711 | // key events, and focus/blur events if autoHideDialCode=true
712 | this.telInput.off(this.ns);
713 | // click event to open dropdown
714 | this.selectedFlagInner.parent().off(this.ns);
715 | // label click hack
716 | this.telInput.closest("label").off(this.ns);
717 | // remove markup
718 | var container = this.telInput.parent();
719 | container.before(this.telInput).remove();
720 | },
721 | // get the country data for the currently selected flag
722 | getSelectedCountryData: function() {
723 | return this.selectedCountryData;
724 | },
725 | // validate the input val - assumes the global function isValidNumber
726 | // pass in true if you want to allow national numbers (no country dial code)
727 | isValidNumber: function(allowNational) {
728 | var val = $.trim(this.telInput.val()), countryCode = allowNational ? this.selectedCountryData.iso2 : "", // libphonenumber allows alpha chars, but in order to allow that, we'd need a method to retrieve the processed number, with letters replaced with numbers
729 | containsAlpha = /[a-zA-Z]/.test(val);
730 | return !containsAlpha && window.intlTelInputUtils && intlTelInputUtils.isValidNumber(val, countryCode);
731 | },
732 | // update the selected flag, and if the input is empty: insert the new dial code
733 | selectCountry: function(countryCode) {
734 | // check if already selected
735 | if (!this.selectedFlagInner.hasClass(countryCode)) {
736 | this._selectFlag(countryCode);
737 | if (!this.telInput.val() && !this.options.autoHideDialCode) {
738 | this._resetToDialCode(this.selectedCountryData.dialCode);
739 | }
740 | }
741 | },
742 | // set the input value and update the flag
743 | setNumber: function(number, addSuffix) {
744 | // we must update the flag first, which updates this.selectedCountryData, which is used later for formatting the number before displaying it
745 | var dialCode = this._updateFlag(number);
746 | this._updateVal(number, addSuffix);
747 | return dialCode;
748 | },
749 | // this is called when the utils are ready
750 | utilsLoaded: function() {
751 | // if autoFormat is enabled and there's an initial value in the input, then format it
752 | if (this.options.autoFormat && this.telInput.val()) {
753 | this._updateVal(this.telInput.val());
754 | }
755 | }
756 | };
757 | // adapted to allow public functions
758 | // using https://github.com/jquery-boilerplate/jquery-boilerplate/wiki/Extending-jQuery-Boilerplate
759 | $.fn[pluginName] = function(options) {
760 | var args = arguments;
761 | // Is the first parameter an object (options), or was omitted,
762 | // instantiate a new instance of the plugin.
763 | if (options === undefined || typeof options === "object") {
764 | return this.each(function() {
765 | if (!$.data(this, "plugin_" + pluginName)) {
766 | $.data(this, "plugin_" + pluginName, new Plugin(this, options));
767 | }
768 | });
769 | } else if (typeof options === "string" && options[0] !== "_" && options !== "init") {
770 | // If the first parameter is a string and it doesn't start
771 | // with an underscore or "contains" the `init`-function,
772 | // treat this as a call to a public method.
773 | // Cache the method call to make it possible to return a value
774 | var returns;
775 | this.each(function() {
776 | var instance = $.data(this, "plugin_" + pluginName);
777 | // Tests that there's already a plugin-instance
778 | // and checks that the requested public method exists
779 | if (instance instanceof Plugin && typeof instance[options] === "function") {
780 | // Call the method of our plugin instance,
781 | // and pass it the supplied arguments.
782 | returns = instance[options].apply(instance, Array.prototype.slice.call(args, 1));
783 | }
784 | // Allow instances to be destroyed via the 'destroy' method
785 | if (options === "destroy") {
786 | $.data(this, "plugin_" + pluginName, null);
787 | }
788 | });
789 | // If the earlier cached method gives a value back return the value,
790 | // otherwise return this to preserve chainability.
791 | return returns !== undefined ? returns : this;
792 | }
793 | };
794 | /********************
795 | * STATIC METHODS
796 | ********************/
797 | // get the country data object
798 | $.fn[pluginName].getCountryData = function() {
799 | return allCountries;
800 | };
801 | // set the country data object
802 | $.fn[pluginName].setCountryData = function(obj) {
803 | allCountries = obj;
804 | };
805 | // Tell JSHint to ignore this warning: "character may get silently deleted by one or more browsers"
806 | // jshint -W100
807 | // Array of country objects for the flag dropdown.
808 | // Each contains a name, country code (ISO 3166-1 alpha-2) and dial code.
809 | // Originally from https://github.com/mledoze/countries
810 | // then modified using the following JavaScript (NOW OUT OF DATE):
811 | /*
812 | var result = [];
813 | _.each(countries, function(c) {
814 | // ignore countries without a dial code
815 | if (c.callingCode[0].length) {
816 | result.push({
817 | // var locals contains country names with localised versions in brackets
818 | n: _.findWhere(locals, {
819 | countryCode: c.cca2
820 | }).name,
821 | i: c.cca2.toLowerCase(),
822 | d: c.callingCode[0]
823 | });
824 | }
825 | });
826 | JSON.stringify(result);
827 | */
828 | // then with a couple of manual re-arrangements to be alphabetical
829 | // then changed Kazakhstan from +76 to +7
830 | // and Vatican City from +379 to +39 (see issue 50)
831 | // and Caribean Netherlands from +5997 to +599
832 | // and Curacao from +5999 to +599
833 | // Removed: Åland Islands, Christmas Island, Cocos Islands, Guernsey, Isle of Man, Jersey, Kosovo, Mayotte, Pitcairn Islands, South Georgia, Svalbard, Western Sahara
834 | // Update: converted objects to arrays to save bytes!
835 | // Update: added "priority" for countries with the same dialCode as others
836 | // Update: added array of area codes for countries with the same dialCode as others
837 | // So each country array has the following information:
838 | // [
839 | // Country name,
840 | // iso2 code,
841 | // International dial code,
842 | // Order (if >1 country with same dial code),
843 | // Area codes (if >1 country with same dial code)
844 | // ]
845 | 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", "236", "249", "250", "289", "306", "343", "365", "387", "403", "416", "418", "431", "437", "438", "450", "506", "514", "519", "548", "579", "581", "587", "604", "613", "639", "647", "672", "705", "709", "742", "778", "780", "782", "807", "819", "825", "867", "873", "902", "905" ] ], [ "Cape Verde (Kabu Verdi)", "cv", "238" ], [ "Caribbean Netherlands", "bq", "599", "", 1 ], [ "Cayman Islands", "ky", "1345" ], [ "Central African Republic (République centrafricaine)", "cf", "236" ], [ "Chad (Tchad)", "td", "235" ], [ "Chile", "cl", "56" ], [ "China (中国)", "cn", "86" ], [ "Colombia", "co", "57" ], [ "Comoros (جزر القمر)", "km", "269" ], [ "Congo (DRC) (Jamhuri ya Kidemokrasia ya Kongo)", "cd", "243" ], [ "Congo (Republic) (Congo-Brazzaville)", "cg", "242" ], [ "Cook Islands", "ck", "682" ], [ "Costa Rica", "cr", "506" ], [ "Côte d’Ivoire", "ci", "225" ], [ "Croatia (Hrvatska)", "hr", "385" ], [ "Cuba", "cu", "53" ], [ "Curaçao", "cw", "599", "", 0 ], [ "Cyprus (Κύπρος)", "cy", "357" ], [ "Czech Republic (Česká republika)", "cz", "420" ], [ "Denmark (Danmark)", "dk", "45" ], [ "Djibouti", "dj", "253" ], [ "Dominica", "dm", "1767" ], [ "Dominican Republic (República Dominicana)", "do", "1", "", 2, [ "809", "829", "849" ] ], [ "Ecuador", "ec", "593" ], [ "Egypt (مصر)", "eg", "20" ], [ "El Salvador", "sv", "503" ], [ "Equatorial Guinea (Guinea Ecuatorial)", "gq", "240" ], [ "Eritrea", "er", "291" ], [ "Estonia (Eesti)", "ee", "372" ], [ "Ethiopia", "et", "251" ], [ "Falkland Islands (Islas Malvinas)", "fk", "500" ], [ "Faroe Islands (Føroyar)", "fo", "298" ], [ "Fiji", "fj", "679" ], [ "Finland (Suomi)", "fi", "358" ], [ "France", "fr", "33" ], [ "French Guiana (Guyane française)", "gf", "594" ], [ "French Polynesia (Polynésie française)", "pf", "689" ], [ "Gabon", "ga", "241" ], [ "Gambia", "gm", "220" ], [ "Georgia (საქართველო)", "ge", "995" ], [ "Germany (Deutschland)", "de", "49" ], [ "Ghana (Gaana)", "gh", "233" ], [ "Gibraltar", "gi", "350" ], [ "Greece (Ελλάδα)", "gr", "30" ], [ "Greenland (Kalaallit Nunaat)", "gl", "299" ], [ "Grenada", "gd", "1473" ], [ "Guadeloupe", "gp", "590", "", 0 ], [ "Guam", "gu", "1671" ], [ "Guatemala", "gt", "502" ], [ "Guinea (Guinée)", "gn", "224" ], [ "Guinea-Bissau (Guiné Bissau)", "gw", "245" ], [ "Guyana", "gy", "592" ], [ "Haiti", "ht", "509" ], [ "Honduras", "hn", "504" ], [ "Hong Kong (香港)", "hk", "852" ], [ "Hungary (Magyarország)", "hu", "36" ], [ "Iceland (Ísland)", "is", "354" ], [ "India (भारत)", "in", "91" ], [ "Indonesia", "id", "62" ], [ "Iran (ایران)", "ir", "98" ], [ "Iraq (العراق)", "iq", "964" ], [ "Ireland", "ie", "353" ], [ "Israel (ישראל)", "il", "972" ], [ "Italy (Italia)", "it", "39", 0 ], [ "Jamaica", "jm", "1876" ], [ "Japan (日本)", "jp", "81" ], [ "Jordan (الأردن)", "jo", "962" ], [ "Kazakhstan (Казахстан)", "kz", "7", 1 ], [ "Kenya", "ke", "254" ], [ "Kiribati", "ki", "686" ], [ "Kuwait (الكويت)", "kw", "965" ], [ "Kyrgyzstan (Кыргызстан)", "kg", "996" ], [ "Laos (ລາວ)", "la", "856" ], [ "Latvia (Latvija)", "lv", "371" ], [ "Lebanon (لبنان)", "lb", "961" ], [ "Lesotho", "ls", "266" ], [ "Liberia", "lr", "231" ], [ "Libya (ليبيا)", "ly", "218" ], [ "Liechtenstein", "li", "423" ], [ "Lithuania (Lietuva)", "lt", "370" ], [ "Luxembourg", "lu", "352" ], [ "Macau (澳門)", "mo", "853" ], [ "Macedonia (FYROM) (Македонија)", "mk", "389" ], [ "Madagascar (Madagasikara)", "mg", "261" ], [ "Malawi", "mw", "265" ], [ "Malaysia", "my", "60" ], [ "Maldives", "mv", "960" ], [ "Mali", "ml", "223" ], [ "Malta", "mt", "356" ], [ "Marshall Islands", "mh", "692" ], [ "Martinique", "mq", "596" ], [ "Mauritania (موريتانيا)", "mr", "222" ], [ "Mauritius (Moris)", "mu", "230" ], [ "Mexico (México)", "mx", "52" ], [ "Micronesia", "fm", "691" ], [ "Moldova (Republica Moldova)", "md", "373" ], [ "Monaco", "mc", "377" ], [ "Mongolia (Монгол)", "mn", "976" ], [ "Montenegro (Crna Gora)", "me", "382" ], [ "Montserrat", "ms", "1664" ], [ "Morocco (المغرب)", "ma", "212" ], [ "Mozambique (Moçambique)", "mz", "258" ], [ "Myanmar (Burma) (မြန်မာ)", "mm", "95" ], [ "Namibia (Namibië)", "na", "264" ], [ "Nauru", "nr", "674" ], [ "Nepal (नेपाल)", "np", "977" ], [ "Netherlands (Nederland)", "nl", "31" ], [ "New Caledonia (Nouvelle-Calédonie)", "nc", "687" ], [ "New Zealand", "nz", "64" ], [ "Nicaragua", "ni", "505" ], [ "Niger (Nijar)", "ne", "227" ], [ "Nigeria", "ng", "234" ], [ "Niue", "nu", "683" ], [ "Norfolk Island", "nf", "672" ], [ "North Korea (조선 민주주의 인민 공화국)", "kp", "850" ], [ "Northern Mariana Islands", "mp", "1670" ], [ "Norway (Norge)", "no", "47" ], [ "Oman (عُمان)", "om", "968" ], [ "Pakistan (پاکستان)", "pk", "92" ], [ "Palau", "pw", "680" ], [ "Palestine (فلسطين)", "ps", "970" ], [ "Panama (Panamá)", "pa", "507" ], [ "Papua New Guinea", "pg", "675" ], [ "Paraguay", "py", "595" ], [ "Peru (Perú)", "pe", "51" ], [ "Philippines", "ph", "63" ], [ "Poland (Polska)", "pl", "48" ], [ "Portugal", "pt", "351" ], [ "Puerto Rico", "pr", "1", "", 3, [ "787", "939" ] ], [ "Qatar (قطر)", "qa", "974" ], [ "Réunion (La Réunion)", "re", "262" ], [ "Romania (România)", "ro", "40" ], [ "Russia (Россия)", "ru", "7", 0 ], [ "Rwanda", "rw", "250" ], [ "Saint Barthélemy (Saint-Barthélemy)", "bl", "590", "", 1 ], [ "Saint Helena", "sh", "290" ], [ "Saint Kitts and Nevis", "kn", "1869" ], [ "Saint Lucia", "lc", "1758" ], [ "Saint Martin (Saint-Martin (partie française))", "mf", "590", "", 2 ], [ "Saint Pierre and Miquelon (Saint-Pierre-et-Miquelon)", "pm", "508" ], [ "Saint Vincent and the Grenadines", "vc", "1784" ], [ "Samoa", "ws", "685" ], [ "San Marino", "sm", "378" ], [ "São Tomé and Príncipe (São Tomé e Príncipe)", "st", "239" ], [ "Saudi Arabia (المملكة العربية السعودية)", "sa", "966" ], [ "Senegal (Sénégal)", "sn", "221" ], [ "Serbia (Србија)", "rs", "381" ], [ "Seychelles", "sc", "248" ], [ "Sierra Leone", "sl", "232" ], [ "Singapore", "sg", "65" ], [ "Sint Maarten", "sx", "1721" ], [ "Slovakia (Slovensko)", "sk", "421" ], [ "Slovenia (Slovenija)", "si", "386" ], [ "Solomon Islands", "sb", "677" ], [ "Somalia (Soomaaliya)", "so", "252" ], [ "South Africa", "za", "27" ], [ "South Korea (대한민국)", "kr", "82" ], [ "South Sudan (جنوب السودان)", "ss", "211" ], [ "Spain (España)", "es", "34" ], [ "Sri Lanka (ශ්රී ලංකාව)", "lk", "94" ], [ "Sudan (السودان)", "sd", "249" ], [ "Suriname", "sr", "597" ], [ "Swaziland", "sz", "268" ], [ "Sweden (Sverige)", "se", "46" ], [ "Switzerland (Schweiz)", "ch", "41" ], [ "Syria (سوريا)", "sy", "963" ], [ "Taiwan (台灣)", "tw", "886" ], [ "Tajikistan", "tj", "992" ], [ "Tanzania", "tz", "255" ], [ "Thailand (ไทย)", "th", "66" ], [ "Timor-Leste", "tl", "670" ], [ "Togo", "tg", "228" ], [ "Tokelau", "tk", "690" ], [ "Tonga", "to", "676" ], [ "Trinidad and Tobago", "tt", "1868" ], [ "Tunisia (تونس)", "tn", "216" ], [ "Turkey (Türkiye)", "tr", "90" ], [ "Turkmenistan", "tm", "993" ], [ "Turks and Caicos Islands", "tc", "1649" ], [ "Tuvalu", "tv", "688" ], [ "U.S. Virgin Islands", "vi", "1340" ], [ "Uganda", "ug", "256" ], [ "Ukraine (Україна)", "ua", "380" ], [ "United Arab Emirates (الإمارات العربية المتحدة)", "ae", "971" ], [ "United Kingdom", "gb", "44" ], [ "United States", "us", "1", 0 ], [ "Uruguay", "uy", "598" ], [ "Uzbekistan (Oʻzbekiston)", "uz", "998" ], [ "Vanuatu", "vu", "678" ], [ "Vatican City (Città del Vaticano)", "va", "39", 1 ], [ "Venezuela", "ve", "58" ], [ "Vietnam (Việt Nam)", "vn", "84" ], [ "Wallis and Futuna", "wf", "681" ], [ "Yemen (اليمن)", "ye", "967" ], [ "Zambia", "zm", "260" ], [ "Zimbabwe", "zw", "263" ] ];
846 | // we will build this in the loop below
847 | var allCountryCodes = {};
848 | var addCountryCode = function(iso2, dialCode, priority) {
849 | if (!(dialCode in allCountryCodes)) {
850 | allCountryCodes[dialCode] = [];
851 | }
852 | var index = priority || 0;
853 | allCountryCodes[dialCode][index] = iso2;
854 | };
855 | // loop over all of the countries above
856 | for (var i = 0; i < allCountries.length; i++) {
857 | // countries
858 | var c = allCountries[i];
859 | allCountries[i] = {
860 | name: c[0],
861 | iso2: c[1],
862 | dialCode: c[2]
863 | };
864 | // area codes
865 | if (c[4]) {
866 | allCountries[i].hasAreaCodes = true;
867 | for (var j = 0; j < c[4].length; j++) {
868 | // full dial code is country code + dial code
869 | var dialCode = c[2] + c[4][j];
870 | addCountryCode(c[1], dialCode);
871 | }
872 | }
873 | // dial codes
874 | addCountryCode(c[1], c[2], c[3]);
875 | }
876 | });
--------------------------------------------------------------------------------