15 if (typeof define ===
'function' && define.amd) {
17 define([
'jquery'], factory);
18 }
else if (typeof exports ===
'object' && typeof require ===
'function') {
20 factory(require(
'jquery'));
29 utils = (
function () {
31 escapeRegExChars:
function (value) {
32 return value.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,
"\\$&");
34 createNode:
function (containerClass) {
35 var div = document.createElement(
'div');
36 div.className = containerClass;
37 div.style.position =
'absolute';
38 div.style.display =
'none';
54 function Autocomplete(el, options) {
55 var noop =
function () { },
59 autoSelectFirst:
false,
60 appendTo: document.body,
69 formatResult: Autocomplete.formatResult,
75 onSearchComplete: noop,
78 containerClass:
'autocomplete-suggestions',
82 triggerSelectOnValidInput:
true,
83 preventBadQueries:
true,
84 lookupFilter:
function (suggestion, originalQuery, queryLowerCase) {
85 return suggestion.value.toLowerCase().indexOf(queryLowerCase) !== -1;
88 transformResult:
function (response) {
89 return typeof response ===
'string' ? $.parseJSON(response) : response;
91 showNoSuggestionNotice:
false,
92 noSuggestionNotice:
'No results',
93 orientation:
'bottom',
94 forceFixPosition:
false
100 that.suggestions = [];
101 that.badQueries = [];
102 that.selectedIndex = -1;
103 that.currentValue = that.element.value;
105 that.cachedResponse = {};
106 that.onChangeInterval = null;
107 that.onChange = null;
108 that.isLocal =
false;
109 that.suggestionsContainer = null;
110 that.noSuggestionsContainer = null;
111 that.options = $.extend({}, defaults, options);
113 selected:
'autocomplete-selected',
114 suggestion:
'autocomplete-suggestion'
118 that.selection = null;
122 that.setOptions(options);
125 Autocomplete.utils = utils;
127 $.Autocomplete = Autocomplete;
129 Autocomplete.formatResult =
function (suggestion, currentValue) {
132 return suggestion.value;
135 var pattern =
'(' + utils.escapeRegExChars(currentValue) +
')';
137 return suggestion.value
138 .replace(
new RegExp(pattern,
'gi'),
'<strong>$1<\/strong>')
139 .replace(/&/g,
'&')
140 .replace(/</g,
'<')
141 .replace(/>/g,
'>')
142 .replace(/
"/g, '"')
143 .replace(/<(\/?strong)>/g, '<$1>');
146 Autocomplete.prototype = {
150 initialize: function () {
152 suggestionSelector = '.' + that.classes.suggestion,
153 selected = that.classes.selected,
154 options = that.options,
157 // Remove autocomplete attribute to prevent native suggestions:
158 that.element.setAttribute('autocomplete', 'off');
160 that.killerFn = function (e) {
161 if ($(e.target).closest('.' + that.options.containerClass).length === 0) {
162 that.killSuggestions();
163 that.disableKillerFn();
167 // html() deals with many types: htmlString or Element or Array or jQuery
168 that.noSuggestionsContainer = $('<div class="autocomplete-no-suggestion
"></div>')
169 .html(this.options.noSuggestionNotice).get(0);
171 that.suggestionsContainer = Autocomplete.utils.createNode(options.containerClass);
173 container = $(that.suggestionsContainer);
175 container.appendTo(options.appendTo);
177 // Only set width if it was provided:
178 if (options.width !== 'auto') {
179 container.width(options.width);
182 // Listen for mouse over event on suggestions list:
183 container.on('mouseover.autocomplete', suggestionSelector, function () {
184 that.activate($(this).data('index'));
187 // Deselect active element when mouse leaves suggestions container:
188 container.on('mouseout.autocomplete', function () {
189 that.selectedIndex = -1;
190 container.children('.' + selected).removeClass(selected);
193 // Listen for click event on suggestions list:
194 container.on('click.autocomplete', suggestionSelector, function () {
195 that.select($(this).data('index'));
198 that.fixPositionCapture = function () {
204 $(window).on('resize.autocomplete', that.fixPositionCapture);
206 that.el.on('keydown.autocomplete', function (e) { that.onKeyPress(e); });
207 that.el.on('keyup.autocomplete', function (e) { that.onKeyUp(e); });
208 that.el.on('blur.autocomplete', function () { that.onBlur(); });
209 that.el.on('focus.autocomplete', function () { that.onFocus(); });
210 that.el.on('change.autocomplete', function (e) { that.onKeyUp(e); });
211 that.el.on('input.autocomplete', function (e) { that.onKeyUp(e); });
214 onFocus: function () {
219 if (that.el.val().length >= that.options.minChars) {
220 that.onValueChange();
224 onBlur: function () {
225 this.enableKillerFn();
228 abortAjax: function () {
230 if (that.currentRequest) {
231 that.currentRequest.abort();
232 that.currentRequest = null;
236 setOptions: function (suppliedOptions) {
238 options = that.options;
240 $.extend(options, suppliedOptions);
242 that.isLocal = $.isArray(options.lookup);
245 options.lookup = that.verifySuggestionsFormat(options.lookup);
248 options.orientation = that.validateOrientation(options.orientation, 'bottom');
250 // Adjust height, width and z-index:
251 $(that.suggestionsContainer).css({
252 'max-height': options.maxHeight + 'px',
253 'width': options.width + 'px',
254 'z-index': options.zIndex
259 clearCache: function () {
260 this.cachedResponse = {};
261 this.badQueries = [];
266 this.currentValue = '';
267 this.suggestions = [];
270 disable: function () {
272 that.disabled = true;
273 clearInterval(that.onChangeInterval);
277 enable: function () {
278 this.disabled = false;
281 fixPosition: function () {
282 // Use only when container has already its content
285 $container = $(that.suggestionsContainer),
286 containerParent = $container.parent().get(0);
287 // Fix position automatically when appended to body.
288 // In other cases force parameter must be given.
289 if (containerParent !== document.body && !that.options.forceFixPosition) {
293 // Choose orientation
294 var orientation = that.options.orientation,
295 containerHeight = $container.outerHeight(),
296 height = that.el.outerHeight(),
297 offset = that.el.offset(),
298 styles = { 'top': offset.top, 'left': offset.left };
300 if (orientation === 'auto') {
301 var viewPortHeight = $(window).height(),
302 scrollTop = $(window).scrollTop(),
303 topOverflow = -scrollTop + offset.top - containerHeight,
304 bottomOverflow = scrollTop + viewPortHeight - (offset.top + height + containerHeight);
306 orientation = (Math.max(topOverflow, bottomOverflow) === topOverflow) ? 'top' : 'bottom';
309 if (orientation === 'top') {
310 styles.top += -containerHeight;
312 styles.top += height;
315 // If container is not positioned to body,
316 // correct its position using offset parent offset
317 if(containerParent !== document.body) {
318 var opacity = $container.css('opacity'),
322 $container.css('opacity', 0).show();
325 parentOffsetDiff = $container.offsetParent().offset();
326 styles.top -= parentOffsetDiff.top;
327 styles.left -= parentOffsetDiff.left;
330 $container.css('opacity', opacity).hide();
334 // -2px to account for suggestions border.
335 if (that.options.width === 'auto') {
336 styles.width = (that.el.outerWidth() - 2) + 'px';
339 $container.css(styles);
342 enableKillerFn: function () {
344 $(document).on('click.autocomplete', that.killerFn);
347 disableKillerFn: function () {
349 $(document).off('click.autocomplete', that.killerFn);
352 killSuggestions: function () {
354 that.stopKillSuggestions();
355 that.intervalId = window.setInterval(function () {
357 that.el.val(that.currentValue);
361 that.stopKillSuggestions();
365 stopKillSuggestions: function () {
366 window.clearInterval(this.intervalId);
369 isCursorAtEnd: function () {
371 valLength = that.el.val().length,
372 selectionStart = that.element.selectionStart,
375 if (typeof selectionStart === 'number') {
376 return selectionStart === valLength;
378 if (document.selection) {
379 range = document.selection.createRange();
380 range.moveStart('character', -valLength);
381 return valLength === range.text.length;
386 onKeyPress: function (e) {
389 // If suggestions are hidden and user presses arrow down, display suggestions:
390 if (!that.disabled && !that.visible && e.which === keys.DOWN && that.currentValue) {
395 if (that.disabled || !that.visible) {
401 that.el.val(that.currentValue);
405 if (that.hint && that.options.onHint && that.isCursorAtEnd()) {
411 if (that.hint && that.options.onHint) {
415 if (that.selectedIndex === -1) {
419 that.select(that.selectedIndex);
420 if (that.options.tabDisabled === false) {
425 if (that.selectedIndex === -1) {
429 that.select(that.selectedIndex);
441 // Cancel event if function did not return:
442 e.stopImmediatePropagation();
446 onKeyUp: function (e) {
459 clearInterval(that.onChangeInterval);
461 if (that.currentValue !== that.el.val()) {
463 if (that.options.deferRequestBy > 0) {
464 // Defer lookup in case when value changes very quickly:
465 that.onChangeInterval = setInterval(function () {
466 that.onValueChange();
467 }, that.options.deferRequestBy);
469 that.onValueChange();
474 onValueChange: function () {
476 options = that.options,
477 value = that.el.val(),
478 query = that.getQuery(value);
480 if (that.selection && that.currentValue !== query) {
481 that.selection = null;
482 (options.onInvalidateSelection || $.noop).call(that.element);
485 clearInterval(that.onChangeInterval);
486 that.currentValue = value;
487 that.selectedIndex = -1;
489 // Check existing suggestion for the match before proceeding:
490 if (options.triggerSelectOnValidInput && that.isExactMatch(query)) {
495 if (query.length < options.minChars) {
498 that.getSuggestions(query);
502 isExactMatch: function (query) {
503 var suggestions = this.suggestions;
505 return (suggestions.length === 1 && suggestions[0].value.toLowerCase() === query.toLowerCase());
508 getQuery: function (value) {
509 var delimiter = this.options.delimiter,
515 parts = value.split(delimiter);
516 return $.trim(parts[parts.length - 1]);
519 getSuggestionsLocal: function (query) {
521 options = that.options,
522 queryLowerCase = query.toLowerCase(),
523 filter = options.lookupFilter,
524 limit = parseInt(options.lookupLimit, 10),
528 suggestions: $.grep(options.lookup, function (suggestion) {
529 return filter(suggestion, query, queryLowerCase);
533 if (limit && data.suggestions.length > limit) {
534 data.suggestions = data.suggestions.slice(0, limit);
540 getSuggestions: function (q) {
543 options = that.options,
544 serviceUrl = options.serviceUrl,
549 options.params[options.paramName] = q;
550 params = options.ignoreParams ? null : options.params;
552 if (options.onSearchStart.call(that.element, options.params) === false) {
556 if ($.isFunction(options.lookup)){
557 options.lookup(q, function (data) {
558 that.suggestions = data.suggestions;
560 options.onSearchComplete.call(that.element, q, data.suggestions);
566 response = that.getSuggestionsLocal(q);
568 if ($.isFunction(serviceUrl)) {
569 serviceUrl = serviceUrl.call(that.element, q);
571 cacheKey = serviceUrl + '?' + $.param(params || {});
572 response = that.cachedResponse[cacheKey];
575 if (response && $.isArray(response.suggestions)) {
576 that.suggestions = response.suggestions;
578 options.onSearchComplete.call(that.element, q, response.suggestions);
579 } else if (!that.isBadQuery(q)) {
586 dataType: options.dataType
589 $.extend(ajaxSettings, options.ajaxSettings);
591 that.currentRequest = $.ajax(ajaxSettings).done(function (data) {
593 that.currentRequest = null;
594 result = options.transformResult(data, q);
595 that.processResponse(result, q, cacheKey);
596 options.onSearchComplete.call(that.element, q, result.suggestions);
597 }).fail(function (jqXHR, textStatus, errorThrown) {
598 options.onSearchError.call(that.element, q, jqXHR, textStatus, errorThrown);
601 options.onSearchComplete.call(that.element, q, []);
605 isBadQuery: function (q) {
606 if (!this.options.preventBadQueries){
610 var badQueries = this.badQueries,
611 i = badQueries.length;
614 if (q.indexOf(badQueries[i]) === 0) {
624 container = $(that.suggestionsContainer);
626 if ($.isFunction(that.options.onHide) && that.visible) {
627 that.options.onHide.call(that.element, container);
630 that.visible = false;
631 that.selectedIndex = -1;
632 clearInterval(that.onChangeInterval);
633 $(that.suggestionsContainer).hide();
634 that.signalHint(null);
637 suggest: function () {
638 if (this.suggestions.length === 0) {
639 if (this.options.showNoSuggestionNotice) {
640 this.noSuggestions();
648 options = that.options,
649 groupBy = options.groupBy,
650 formatResult = options.formatResult,
651 value = that.getQuery(that.currentValue),
652 className = that.classes.suggestion,
653 classSelected = that.classes.selected,
654 container = $(that.suggestionsContainer),
655 noSuggestionsContainer = $(that.noSuggestionsContainer),
656 beforeRender = options.beforeRender,
659 formatGroup = function (suggestion, index) {
660 var currentCategory = suggestion.data[groupBy];
662 if (category === currentCategory){
666 category = currentCategory;
668 return '<div class="autocomplete-group
"><strong>' + category + '</strong></div>';
671 if (options.triggerSelectOnValidInput && that.isExactMatch(value)) {
676 // Build suggestions inner HTML:
677 $.each(that.suggestions, function (i, suggestion) {
679 html += formatGroup(suggestion, value, i);
682 html += '<div class="' + className + '" data-index="' + i + '">' + formatResult(suggestion, value) + '</div>';
685 this.adjustContainerWidth();
687 noSuggestionsContainer.detach();
688 container.html(html);
690 if ($.isFunction(beforeRender)) {
691 beforeRender.call(that.element, container);
697 // Select first value by default:
698 if (options.autoSelectFirst) {
699 that.selectedIndex = 0;
700 container.scrollTop(0);
701 container.children('.' + className).first().addClass(classSelected);
708 noSuggestions: function() {
710 container = $(that.suggestionsContainer),
711 noSuggestionsContainer = $(that.noSuggestionsContainer);
713 this.adjustContainerWidth();
715 // Some explicit steps. Be careful here as it easy to get
716 // noSuggestionsContainer removed from DOM if not detached properly.
717 noSuggestionsContainer.detach();
718 container.empty(); // clean suggestions if any
719 container.append(noSuggestionsContainer);
727 adjustContainerWidth: function() {
729 options = that.options,
731 container = $(that.suggestionsContainer);
733 // If width is auto, adjust width before displaying suggestions,
734 // because if instance was created before input had width, it will be zero.
735 // Also it adjusts if input width has changed.
736 // -2px to account for suggestions border.
737 if (options.width === 'auto') {
738 width = that.el.outerWidth() - 2;
739 container.width(width > 0 ? width : 300);
743 findBestHint: function () {
745 value = that.el.val().toLowerCase(),
752 $.each(that.suggestions, function (i, suggestion) {
753 var foundMatch = suggestion.value.toLowerCase().indexOf(value) === 0;
755 bestMatch = suggestion;
760 that.signalHint(bestMatch);
763 signalHint: function (suggestion) {
767 hintValue = that.currentValue + suggestion.value.substr(that.currentValue.length);
769 if (that.hintValue !== hintValue) {
770 that.hintValue = hintValue;
771 that.hint = suggestion;
772 (this.options.onHint || $.noop)(hintValue);
776 verifySuggestionsFormat: function (suggestions) {
777 // If suggestions is string array, convert them to supported format:
778 if (suggestions.length && typeof suggestions[0] === 'string') {
779 return $.map(suggestions, function (value) {
780 return { value: value, data: null };
787 validateOrientation: function(orientation, fallback) {
788 orientation = $.trim(orientation || '').toLowerCase();
790 if($.inArray(orientation, ['auto', 'bottom', 'top']) === -1){
791 orientation = fallback;
797 processResponse: function (result, originalQuery, cacheKey) {
799 options = that.options;
801 result.suggestions = that.verifySuggestionsFormat(result.suggestions);
803 // Cache results if cache is not disabled:
804 if (!options.noCache) {
805 that.cachedResponse[cacheKey] = result;
806 if (options.preventBadQueries && result.suggestions.length === 0) {
807 that.badQueries.push(originalQuery);
811 // Return if originalQuery is not matching current query:
812 if (originalQuery !== that.getQuery(that.currentValue)) {
816 that.suggestions = result.suggestions;
820 activate: function (index) {
823 selected = that.classes.selected,
824 container = $(that.suggestionsContainer),
825 children = container.find('.' + that.classes.suggestion);
827 container.find('.' + selected).removeClass(selected);
829 that.selectedIndex = index;
831 if (that.selectedIndex !== -1 && children.length > that.selectedIndex) {
832 activeItem = children.get(that.selectedIndex);
833 $(activeItem).addClass(selected);
840 selectHint: function () {
842 i = $.inArray(that.hint, that.suggestions);
847 select: function (i) {
853 moveUp: function () {
856 if (that.selectedIndex === -1) {
860 if (that.selectedIndex === 0) {
861 $(that.suggestionsContainer).children().first().removeClass(that.classes.selected);
862 that.selectedIndex = -1;
863 that.el.val(that.currentValue);
868 that.adjustScroll(that.selectedIndex - 1);
871 moveDown: function () {
874 if (that.selectedIndex === (that.suggestions.length - 1)) {
878 that.adjustScroll(that.selectedIndex + 1);
881 adjustScroll: function (index) {
883 activeItem = that.activate(index);
892 heightDelta = $(activeItem).outerHeight();
894 offsetTop = activeItem.offsetTop;
895 upperBound = $(that.suggestionsContainer).scrollTop();
896 lowerBound = upperBound + that.options.maxHeight - heightDelta;
898 if (offsetTop < upperBound) {
899 $(that.suggestionsContainer).scrollTop(offsetTop);
900 } else if (offsetTop > lowerBound) {
901 $(that.suggestionsContainer).scrollTop(offsetTop - that.options.maxHeight + heightDelta);
904 if (!that.options.preserveInput) {
905 that.el.val(that.getValue(that.suggestions[index].value));
907 that.signalHint(null);
910 onSelect: function (index) {
912 onSelectCallback = that.options.onSelect,
913 suggestion = that.suggestions[index];
915 that.currentValue = that.getValue(suggestion.value);
917 if (that.currentValue !== that.el.val() && !that.options.preserveInput) {
918 that.el.val(that.currentValue);
921 that.signalHint(null);
922 that.suggestions = [];
923 that.selection = suggestion;
925 if ($.isFunction(onSelectCallback)) {
926 onSelectCallback.call(that.element, suggestion);
930 getValue: function (value) {
932 delimiter = that.options.delimiter,
940 currentValue = that.currentValue;
941 parts = currentValue.split(delimiter);
943 if (parts.length === 1) {
947 return currentValue.substr(0, currentValue.length - parts[parts.length - 1].length) + value;
950 dispose: function () {
952 that.el.off('.autocomplete').removeData('autocomplete');
953 that.disableKillerFn();
954 $(window).off('resize.autocomplete', that.fixPositionCapture);
955 $(that.suggestionsContainer).remove();
959 // Create chainable jQuery plugin:
960 $.fn.autocomplete = $.fn.devbridgeAutocomplete = function (options, args) {
961 var dataKey = 'autocomplete';
962 // If function invoked without argument return
963 // instance of the first matched element:
964 if (arguments.length === 0) {
965 return this.first().data(dataKey);
968 return this.each(function () {
969 var inputElement = $(this),
970 instance = inputElement.data(dataKey);
972 if (typeof options === 'string') {
973 if (instance && typeof instance[options] === 'function') {
974 instance[options](args);
977 // If instance already exists, destroy it:
978 if (instance && instance.dispose) {
981 instance = new Autocomplete(this, options);
982 inputElement.data(dataKey, instance);