2 * Ajax Autocomplete for jQuery, version 1.4.1
5 * Ajax Autocomplete for jQuery is freely distributable under the terms of an MIT-style license.
6 * For details, see the web site: https://github.com/devbridge/jQuery-Autocomplete
9 /*jslint browser: true, white: true, single: true, this: true, multivar: true */
10 /*global define, window, document, jQuery, exports, require */
12 // Expose plugin as an AMD module if AMD loader is present:
15 if (typeof define === 'function' && define.amd) {
16 // AMD. Register as an anonymous module.
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';
56 function Autocomplete(el, options) {
62 that.suggestions = [];
64 that.selectedIndex = -1;
65 that.currentValue = that.element.value;
66 that.timeoutId = null;
67 that.cachedResponse = {};
68 that.onChangeTimeout = null;
71 that.suggestionsContainer = null;
72 that.noSuggestionsContainer = null;
73 that.options = $.extend({}, Autocomplete.defaults, options);
75 selected: 'autocomplete-selected',
76 suggestion: 'autocomplete-suggestion'
80 that.selection = null;
82 // Initialize and set options:
84 that.setOptions(options);
87 Autocomplete.utils = utils;
89 $.Autocomplete = Autocomplete;
91 Autocomplete.defaults = {
93 autoSelectFirst: false,
103 formatResult: _formatResult,
104 formatGroup: _formatGroup,
110 onSearchComplete: noop,
112 preserveInput: false,
113 containerClass: 'autocomplete-suggestions',
116 currentRequest: null,
117 triggerSelectOnValidInput: true,
118 preventBadQueries: true,
119 lookupFilter: _lookupFilter,
121 transformResult: _transformResult,
122 showNoSuggestionNotice: false,
123 noSuggestionNotice: 'No results',
124 orientation: 'bottom',
125 forceFixPosition: false
128 function _lookupFilter(suggestion, originalQuery, queryLowerCase) {
129 return suggestion.value.toLowerCase().indexOf(queryLowerCase) !== -1;
132 function _transformResult(response) {
133 return typeof response === 'string' ? $.parseJSON(response) : response;
136 function _formatResult(suggestion, currentValue) {
137 // Do not replace anything if the current value is empty
139 return suggestion.value;
142 var pattern = '(' + utils.escapeRegExChars(currentValue) + ')';
144 return suggestion.value
145 .replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>')
146 .replace(/&/g, '&')
147 .replace(/</g, '<')
148 .replace(/>/g, '>')
149 .replace(/"/g, '"')
150 .replace(/<(\/?strong)>/g, '<$1>');
153 function _formatGroup(suggestion, category) {
154 return '<div class="autocomplete-group">' + category + '</div>';
157 Autocomplete.prototype = {
159 initialize: function () {
161 suggestionSelector = '.' + that.classes.suggestion,
162 selected = that.classes.selected,
163 options = that.options,
166 // Remove autocomplete attribute to prevent native suggestions:
167 that.element.setAttribute('autocomplete', 'off');
169 // html() deals with many types: htmlString or Element or Array or jQuery
170 that.noSuggestionsContainer = $('<div class="autocomplete-no-suggestion"></div>')
171 .html(this.options.noSuggestionNotice).get(0);
173 that.suggestionsContainer = Autocomplete.utils.createNode(options.containerClass);
175 container = $(that.suggestionsContainer);
177 container.appendTo(options.appendTo || 'body');
179 // Only set width if it was provided:
180 if (options.width !== 'auto') {
181 container.css('width', options.width);
184 // Listen for mouse over event on suggestions list:
185 container.on('mouseover.autocomplete', suggestionSelector, function () {
186 that.activate($(this).data('index'));
189 // Deselect active element when mouse leaves suggestions container:
190 container.on('mouseout.autocomplete', function () {
191 that.selectedIndex = -1;
192 container.children('.' + selected).removeClass(selected);
196 // Listen for click event on suggestions list:
197 container.on('click.autocomplete', suggestionSelector, function () {
198 that.select($(this).data('index'));
201 container.on('click.autocomplete', function () {
202 clearTimeout(that.blurTimeoutId);
205 that.fixPositionCapture = function () {
211 $(window).on('resize.autocomplete', that.fixPositionCapture);
213 that.el.on('keydown.autocomplete', function (e) { that.onKeyPress(e); });
214 that.el.on('keyup.autocomplete', function (e) { that.onKeyUp(e); });
215 that.el.on('blur.autocomplete', function () { that.onBlur(); });
216 that.el.on('focus.autocomplete', function () { that.onFocus(); });
217 that.el.on('change.autocomplete', function (e) { that.onKeyUp(e); });
218 that.el.on('input.autocomplete', function (e) { that.onKeyUp(e); });
221 onFocus: function () {
226 if (that.el.val().length >= that.options.minChars) {
227 that.onValueChange();
231 onBlur: function () {
234 // If user clicked on a suggestion, hide() will
235 // be canceled, otherwise close suggestions
236 that.blurTimeoutId = setTimeout(function () {
241 abortAjax: function () {
243 if (that.currentRequest) {
244 that.currentRequest.abort();
245 that.currentRequest = null;
249 setOptions: function (suppliedOptions) {
251 options = that.options;
253 this.options = $.extend({}, options, suppliedOptions);
255 that.isLocal = $.isArray(options.lookup);
258 options.lookup = that.verifySuggestionsFormat(options.lookup);
261 options.orientation = that.validateOrientation(options.orientation, 'bottom');
263 // Adjust height, width and z-index:
264 $(that.suggestionsContainer).css({
265 'max-height': options.maxHeight + 'px',
266 'width': options.width + 'px',
267 'z-index': options.zIndex
272 clearCache: function () {
273 this.cachedResponse = {};
274 this.badQueries = [];
279 this.currentValue = '';
280 this.suggestions = [];
283 disable: function () {
285 that.disabled = true;
286 clearTimeout(that.onChangeTimeout);
290 enable: function () {
291 this.disabled = false;
294 fixPosition: function () {
295 // Use only when container has already its content
298 $container = $(that.suggestionsContainer),
299 containerParent = $container.parent().get(0);
300 // Fix position automatically when appended to body.
301 // In other cases force parameter must be given.
302 if (containerParent !== document.body && !that.options.forceFixPosition) {
306 // Choose orientation
307 var orientation = that.options.orientation,
308 containerHeight = $container.outerHeight(),
309 height = that.el.outerHeight(),
310 offset = that.el.offset(),
311 styles = { 'top': offset.top, 'left': offset.left };
313 if (orientation === 'auto') {
314 var viewPortHeight = $(window).height(),
315 scrollTop = $(window).scrollTop(),
316 topOverflow = -scrollTop + offset.top - containerHeight,
317 bottomOverflow = scrollTop + viewPortHeight - (offset.top + height + containerHeight);
319 orientation = (Math.max(topOverflow, bottomOverflow) === topOverflow) ? 'top' : 'bottom';
322 if (orientation === 'top') {
323 styles.top += -containerHeight;
325 styles.top += height;
328 // If container is not positioned to body,
329 // correct its position using offset parent offset
330 if(containerParent !== document.body) {
331 var opacity = $container.css('opacity'),
335 $container.css('opacity', 0).show();
338 parentOffsetDiff = $container.offsetParent().offset();
339 styles.top -= parentOffsetDiff.top;
340 styles.left -= parentOffsetDiff.left;
343 $container.css('opacity', opacity).hide();
347 if (that.options.width === 'auto') {
348 styles.width = that.el.outerWidth() + 'px';
351 $container.css(styles);
354 isCursorAtEnd: function () {
356 valLength = that.el.val().length,
357 selectionStart = that.element.selectionStart,
360 if (typeof selectionStart === 'number') {
361 return selectionStart === valLength;
363 if (document.selection) {
364 range = document.selection.createRange();
365 range.moveStart('character', -valLength);
366 return valLength === range.text.length;
371 onKeyPress: function (e) {
374 // If suggestions are hidden and user presses arrow down, display suggestions:
375 if (!that.disabled && !that.visible && e.which === keys.DOWN && that.currentValue) {
380 if (that.disabled || !that.visible) {
386 that.el.val(that.currentValue);
390 if (that.hint && that.options.onHint && that.isCursorAtEnd()) {
396 if (that.hint && that.options.onHint) {
400 if (that.selectedIndex === -1) {
404 that.select(that.selectedIndex);
405 if (that.options.tabDisabled === false) {
410 if (that.selectedIndex === -1) {
414 that.select(that.selectedIndex);
426 // Cancel event if function did not return:
427 e.stopImmediatePropagation();
431 onKeyUp: function (e) {
444 clearTimeout(that.onChangeTimeout);
446 if (that.currentValue !== that.el.val()) {
448 if (that.options.deferRequestBy > 0) {
449 // Defer lookup in case when value changes very quickly:
450 that.onChangeTimeout = setTimeout(function () {
451 that.onValueChange();
452 }, that.options.deferRequestBy);
454 that.onValueChange();
459 onValueChange: function () {
461 options = that.options,
462 value = that.el.val(),
463 query = that.getQuery(value);
465 if (that.selection && that.currentValue !== query) {
466 that.selection = null;
467 (options.onInvalidateSelection || $.noop).call(that.element);
470 clearTimeout(that.onChangeTimeout);
471 that.currentValue = value;
472 that.selectedIndex = -1;
474 // Check existing suggestion for the match before proceeding:
475 if (options.triggerSelectOnValidInput && that.isExactMatch(query)) {
480 if (query.length < options.minChars) {
483 that.getSuggestions(query);
487 isExactMatch: function (query) {
488 var suggestions = this.suggestions;
490 return (suggestions.length === 1 && suggestions[0].value.toLowerCase() === query.toLowerCase());
493 getQuery: function (value) {
494 var delimiter = this.options.delimiter,
500 parts = value.split(delimiter);
501 return $.trim(parts[parts.length - 1]);
504 getSuggestionsLocal: function (query) {
506 options = that.options,
507 queryLowerCase = query.toLowerCase(),
508 filter = options.lookupFilter,
509 limit = parseInt(options.lookupLimit, 10),
513 suggestions: $.grep(options.lookup, function (suggestion) {
514 return filter(suggestion, query, queryLowerCase);
518 if (limit && data.suggestions.length > limit) {
519 data.suggestions = data.suggestions.slice(0, limit);
525 getSuggestions: function (q) {
528 options = that.options,
529 serviceUrl = options.serviceUrl,
534 options.params[options.paramName] = q;
536 if (options.onSearchStart.call(that.element, options.params) === false) {
540 params = options.ignoreParams ? null : options.params;
542 if ($.isFunction(options.lookup)){
543 options.lookup(q, function (data) {
544 that.suggestions = data.suggestions;
546 options.onSearchComplete.call(that.element, q, data.suggestions);
552 response = that.getSuggestionsLocal(q);
554 if ($.isFunction(serviceUrl)) {
555 serviceUrl = serviceUrl.call(that.element, q);
557 cacheKey = serviceUrl + '?' + $.param(params || {});
558 response = that.cachedResponse[cacheKey];
561 if (response && $.isArray(response.suggestions)) {
562 that.suggestions = response.suggestions;
564 options.onSearchComplete.call(that.element, q, response.suggestions);
565 } else if (!that.isBadQuery(q)) {
572 dataType: options.dataType
575 $.extend(ajaxSettings, options.ajaxSettings);
577 that.currentRequest = $.ajax(ajaxSettings).done(function (data) {
579 that.currentRequest = null;
580 result = options.transformResult(data, q);
581 that.processResponse(result, q, cacheKey);
582 options.onSearchComplete.call(that.element, q, result.suggestions);
583 }).fail(function (jqXHR, textStatus, errorThrown) {
584 options.onSearchError.call(that.element, q, jqXHR, textStatus, errorThrown);
587 options.onSearchComplete.call(that.element, q, []);
591 isBadQuery: function (q) {
592 if (!this.options.preventBadQueries){
596 var badQueries = this.badQueries,
597 i = badQueries.length;
600 if (q.indexOf(badQueries[i]) === 0) {
610 container = $(that.suggestionsContainer);
612 if ($.isFunction(that.options.onHide) && that.visible) {
613 that.options.onHide.call(that.element, container);
616 that.visible = false;
617 that.selectedIndex = -1;
618 clearTimeout(that.onChangeTimeout);
619 $(that.suggestionsContainer).hide();
620 that.signalHint(null);
623 suggest: function () {
624 if (!this.suggestions.length) {
625 if (this.options.showNoSuggestionNotice) {
626 this.noSuggestions();
634 options = that.options,
635 groupBy = options.groupBy,
636 formatResult = options.formatResult,
637 value = that.getQuery(that.currentValue),
638 className = that.classes.suggestion,
639 classSelected = that.classes.selected,
640 container = $(that.suggestionsContainer),
641 noSuggestionsContainer = $(that.noSuggestionsContainer),
642 beforeRender = options.beforeRender,
645 formatGroup = function (suggestion, index) {
646 var currentCategory = suggestion.data[groupBy];
648 if (category === currentCategory){
652 category = currentCategory;
654 return options.formatGroup(suggestion, category);
657 if (options.triggerSelectOnValidInput && that.isExactMatch(value)) {
662 // Build suggestions inner HTML:
663 $.each(that.suggestions, function (i, suggestion) {
665 html += formatGroup(suggestion, value, i);
668 html += '<div class="' + className + '" data-index="' + i + '">' + formatResult(suggestion, value, i) + '</div>';
671 this.adjustContainerWidth();
673 noSuggestionsContainer.detach();
674 container.html(html);
676 if ($.isFunction(beforeRender)) {
677 beforeRender.call(that.element, container, that.suggestions);
683 // Select first value by default:
684 if (options.autoSelectFirst) {
685 that.selectedIndex = 0;
686 container.scrollTop(0);
687 container.children('.' + className).first().addClass(classSelected);
694 noSuggestions: function() {
696 beforeRender = that.options.beforeRender,
697 container = $(that.suggestionsContainer),
698 noSuggestionsContainer = $(that.noSuggestionsContainer);
700 this.adjustContainerWidth();
702 // Some explicit steps. Be careful here as it easy to get
703 // noSuggestionsContainer removed from DOM if not detached properly.
704 noSuggestionsContainer.detach();
706 // clean suggestions if any
708 container.append(noSuggestionsContainer);
710 if ($.isFunction(beforeRender)) {
711 beforeRender.call(that.element, container, that.suggestions);
720 adjustContainerWidth: function() {
722 options = that.options,
724 container = $(that.suggestionsContainer);
726 // If width is auto, adjust width before displaying suggestions,
727 // because if instance was created before input had width, it will be zero.
728 // Also it adjusts if input width has changed.
729 if (options.width === 'auto') {
730 width = that.el.outerWidth();
731 container.css('width', width > 0 ? width : 300);
732 } else if(options.width === 'flex') {
733 // Trust the source! Unset the width property so it will be the max length
734 // the containing elements.
735 container.css('width', '');
739 findBestHint: function () {
741 value = that.el.val().toLowerCase(),
748 $.each(that.suggestions, function (i, suggestion) {
749 var foundMatch = suggestion.value.toLowerCase().indexOf(value) === 0;
751 bestMatch = suggestion;
756 that.signalHint(bestMatch);
759 signalHint: function (suggestion) {
763 hintValue = that.currentValue + suggestion.value.substr(that.currentValue.length);
765 if (that.hintValue !== hintValue) {
766 that.hintValue = hintValue;
767 that.hint = suggestion;
768 (this.options.onHint || $.noop)(hintValue);
772 verifySuggestionsFormat: function (suggestions) {
773 // If suggestions is string array, convert them to supported format:
774 if (suggestions.length && typeof suggestions[0] === 'string') {
775 return $.map(suggestions, function (value) {
776 return { value: value, data: null };
783 validateOrientation: function(orientation, fallback) {
784 orientation = $.trim(orientation || '').toLowerCase();
786 if($.inArray(orientation, ['auto', 'bottom', 'top']) === -1){
787 orientation = fallback;
793 processResponse: function (result, originalQuery, cacheKey) {
795 options = that.options;
797 result.suggestions = that.verifySuggestionsFormat(result.suggestions);
799 // Cache results if cache is not disabled:
800 if (!options.noCache) {
801 that.cachedResponse[cacheKey] = result;
802 if (options.preventBadQueries && !result.suggestions.length) {
803 that.badQueries.push(originalQuery);
807 // Return if originalQuery is not matching current query:
808 if (originalQuery !== that.getQuery(that.currentValue)) {
812 that.suggestions = result.suggestions;
816 activate: function (index) {
819 selected = that.classes.selected,
820 container = $(that.suggestionsContainer),
821 children = container.find('.' + that.classes.suggestion);
823 container.find('.' + selected).removeClass(selected);
825 that.selectedIndex = index;
827 if (that.selectedIndex !== -1 && children.length > that.selectedIndex) {
828 activeItem = children.get(that.selectedIndex);
829 $(activeItem).addClass(selected);
836 selectHint: function () {
838 i = $.inArray(that.hint, that.suggestions);
843 select: function (i) {
849 moveUp: function () {
852 if (that.selectedIndex === -1) {
856 if (that.selectedIndex === 0) {
857 $(that.suggestionsContainer).children().first().removeClass(that.classes.selected);
858 that.selectedIndex = -1;
859 that.el.val(that.currentValue);
864 that.adjustScroll(that.selectedIndex - 1);
867 moveDown: function () {
870 if (that.selectedIndex === (that.suggestions.length - 1)) {
874 that.adjustScroll(that.selectedIndex + 1);
877 adjustScroll: function (index) {
879 activeItem = that.activate(index);
888 heightDelta = $(activeItem).outerHeight();
890 offsetTop = activeItem.offsetTop;
891 upperBound = $(that.suggestionsContainer).scrollTop();
892 lowerBound = upperBound + that.options.maxHeight - heightDelta;
894 if (offsetTop < upperBound) {
895 $(that.suggestionsContainer).scrollTop(offsetTop);
896 } else if (offsetTop > lowerBound) {
897 $(that.suggestionsContainer).scrollTop(offsetTop - that.options.maxHeight + heightDelta);
900 if (!that.options.preserveInput) {
901 that.el.val(that.getValue(that.suggestions[index].value));
903 that.signalHint(null);
906 onSelect: function (index) {
908 onSelectCallback = that.options.onSelect,
909 suggestion = that.suggestions[index];
911 that.currentValue = that.getValue(suggestion.value);
913 if (that.currentValue !== that.el.val() && !that.options.preserveInput) {
914 that.el.val(that.currentValue);
917 that.signalHint(null);
918 that.suggestions = [];
919 that.selection = suggestion;
921 if ($.isFunction(onSelectCallback)) {
922 onSelectCallback.call(that.element, suggestion);
926 getValue: function (value) {
928 delimiter = that.options.delimiter,
936 currentValue = that.currentValue;
937 parts = currentValue.split(delimiter);
939 if (parts.length === 1) {
943 return currentValue.substr(0, currentValue.length - parts[parts.length - 1].length) + value;
946 dispose: function () {
948 that.el.off('.autocomplete').removeData('autocomplete');
949 $(window).off('resize.autocomplete', that.fixPositionCapture);
950 $(that.suggestionsContainer).remove();
954 // Create chainable jQuery plugin:
955 $.fn.devbridgeAutocomplete = function (options, args) {
956 var dataKey = 'autocomplete';
957 // If function invoked without argument return
958 // instance of the first matched element:
959 if (!arguments.length) {
960 return this.first().data(dataKey);
963 return this.each(function () {
964 var inputElement = $(this),
965 instance = inputElement.data(dataKey);
967 if (typeof options === 'string') {
968 if (instance && typeof instance[options] === 'function') {
969 instance[options](args);
972 // If instance already exists, destroy it:
973 if (instance && instance.dispose) {
976 instance = new Autocomplete(this, options);
977 inputElement.data(dataKey, instance);
982 // Don't overwrite if it already exists
983 if (!$.fn.autocomplete) {
984 $.fn.autocomplete = $.fn.devbridgeAutocomplete;