2
0
mirror of https://github.com/devbridge/jQuery-Autocomplete.git synced 2024-11-09 23:01:00 +00:00
jQuery-Autocomplete/dist/jquery.autocomplete.js

987 lines
32 KiB
JavaScript
Raw Normal View History

/**
2016-06-14 21:17:00 +00:00
* Ajax Autocomplete for jQuery, version 1.2.25
2015-03-04 16:52:04 +00:00
* (c) 2015 Tomas Kirda
*
* Ajax Autocomplete for jQuery is freely distributable under the terms of an MIT-style license.
2013-11-23 23:26:19 +00:00
* For details, see the web site: https://github.com/devbridge/jQuery-Autocomplete
*/
2014-11-25 01:41:25 +00:00
/*jslint browser: true, white: true, plusplus: true, vars: true */
/*global define, window, document, jQuery, exports, require */
2013-01-15 18:25:11 +00:00
// Expose plugin as an AMD module if AMD loader is present:
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof exports === 'object' && typeof require === 'function') {
// Browserify
factory(require('jquery'));
2013-01-15 18:25:11 +00:00
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
'use strict';
2013-01-15 18:25:11 +00:00
var
utils = (function () {
return {
2013-11-23 23:26:19 +00:00
escapeRegExChars: function (value) {
return value.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
2013-01-15 18:25:11 +00:00
},
2013-11-23 23:26:19 +00:00
createNode: function (containerClass) {
2013-01-15 18:25:11 +00:00
var div = document.createElement('div');
2013-11-23 23:26:19 +00:00
div.className = containerClass;
div.style.position = 'absolute';
div.style.display = 'none';
return div;
}
2013-01-15 18:25:11 +00:00
};
}()),
keys = {
ESC: 27,
TAB: 9,
RETURN: 13,
2013-11-23 23:26:19 +00:00
LEFT: 37,
2013-01-15 18:25:11 +00:00
UP: 38,
2013-11-23 23:26:19 +00:00
RIGHT: 39,
2013-01-15 18:25:11 +00:00
DOWN: 40
};
function Autocomplete(el, options) {
2013-01-15 18:25:11 +00:00
var noop = function () { },
that = this,
defaults = {
ajaxSettings: {},
2013-01-21 00:53:04 +00:00
autoSelectFirst: false,
2014-08-18 13:57:03 +00:00
appendTo: document.body,
2012-12-19 20:44:48 +00:00
serviceUrl: null,
lookup: null,
onSelect: null,
width: 'auto',
minChars: 1,
maxHeight: 300,
deferRequestBy: 0,
params: {},
formatResult: Autocomplete.formatResult,
delimiter: null,
zIndex: 9999,
type: 'GET',
2013-01-15 18:25:11 +00:00
noCache: false,
onSearchStart: noop,
onSearchComplete: noop,
2013-11-23 23:26:19 +00:00
onSearchError: noop,
2014-12-03 20:23:24 +00:00
preserveInput: false,
2013-01-15 18:25:11 +00:00
containerClass: 'autocomplete-suggestions',
2013-01-21 00:53:04 +00:00
tabDisabled: false,
2013-03-27 19:01:24 +00:00
dataType: 'text',
2013-11-23 23:26:19 +00:00
currentRequest: null,
2013-11-24 16:21:19 +00:00
triggerSelectOnValidInput: true,
2014-08-18 13:57:03 +00:00
preventBadQueries: true,
2013-01-15 18:25:11 +00:00
lookupFilter: function (suggestion, originalQuery, queryLowerCase) {
return suggestion.value.toLowerCase().indexOf(queryLowerCase) !== -1;
2013-01-21 00:53:04 +00:00
},
paramName: 'query',
transformResult: function (response) {
2013-03-27 19:01:24 +00:00
return typeof response === 'string' ? $.parseJSON(response) : response;
2014-08-18 13:57:03 +00:00
},
showNoSuggestionNotice: false,
noSuggestionNotice: 'No results',
orientation: 'bottom',
forceFixPosition: false
};
// Shared variables:
that.element = el;
that.el = $(el);
that.suggestions = [];
that.badQueries = [];
that.selectedIndex = -1;
that.currentValue = that.element.value;
that.intervalId = 0;
2013-11-24 16:21:19 +00:00
that.cachedResponse = {};
that.onChangeInterval = null;
that.onChange = null;
that.isLocal = false;
that.suggestionsContainer = null;
2014-08-18 13:57:03 +00:00
that.noSuggestionsContainer = null;
2013-01-21 00:53:04 +00:00
that.options = $.extend({}, defaults, options);
that.classes = {
selected: 'autocomplete-selected',
suggestion: 'autocomplete-suggestion'
};
2013-11-23 23:26:19 +00:00
that.hint = null;
that.hintValue = '';
that.selection = null;
// Initialize and set options:
that.initialize();
that.setOptions(options);
}
Autocomplete.utils = utils;
$.Autocomplete = Autocomplete;
Autocomplete.formatResult = function (suggestion, currentValue) {
2016-06-14 21:17:00 +00:00
// Do not replace anything if there current value is empty
if (!currentValue) {
return suggestion.value;
}
2015-08-20 01:06:22 +00:00
2016-06-14 21:17:00 +00:00
var pattern = '(' + utils.escapeRegExChars(currentValue) + ')';
2015-08-20 01:06:22 +00:00
return suggestion.value
.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>')
2015-03-24 09:14:39 +00:00
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
2015-08-20 01:06:22 +00:00
.replace(/"/g, '&quot;')
.replace(/&lt;(\/?strong)&gt;/g, '<$1>');
};
Autocomplete.prototype = {
killerFn: null,
initialize: function () {
var that = this,
2013-01-15 18:25:11 +00:00
suggestionSelector = '.' + that.classes.suggestion,
2013-01-21 00:53:04 +00:00
selected = that.classes.selected,
options = that.options,
container;
// Remove autocomplete attribute to prevent native suggestions:
2013-01-15 18:25:11 +00:00
that.element.setAttribute('autocomplete', 'off');
2013-01-15 18:25:11 +00:00
that.killerFn = function (e) {
if ($(e.target).closest('.' + that.options.containerClass).length === 0) {
that.killSuggestions();
that.disableKillerFn();
}
};
2014-08-18 13:57:03 +00:00
// html() deals with many types: htmlString or Element or Array or jQuery
that.noSuggestionsContainer = $('<div class="autocomplete-no-suggestion"></div>')
.html(this.options.noSuggestionNotice).get(0);
2013-11-23 23:26:19 +00:00
that.suggestionsContainer = Autocomplete.utils.createNode(options.containerClass);
2013-01-15 18:25:11 +00:00
container = $(that.suggestionsContainer);
2013-11-23 23:26:19 +00:00
container.appendTo(options.appendTo);
// Only set width if it was provided:
if (options.width !== 'auto') {
container.width(options.width);
}
// Listen for mouse over event on suggestions list:
2013-04-24 20:57:23 +00:00
container.on('mouseover.autocomplete', suggestionSelector, function () {
that.activate($(this).data('index'));
});
2013-01-21 00:53:04 +00:00
// Deselect active element when mouse leaves suggestions container:
2013-04-24 20:57:23 +00:00
container.on('mouseout.autocomplete', function () {
2013-01-21 00:53:04 +00:00
that.selectedIndex = -1;
container.children('.' + selected).removeClass(selected);
});
// Listen for click event on suggestions list:
2013-04-24 20:57:23 +00:00
container.on('click.autocomplete', suggestionSelector, function () {
2013-11-23 23:26:19 +00:00
that.select($(this).data('index'));
2016-06-14 21:17:00 +00:00
return false;
});
2013-11-23 23:26:19 +00:00
that.fixPositionCapture = function () {
if (that.visible) {
that.fixPosition();
}
};
$(window).on('resize.autocomplete', that.fixPositionCapture);
2013-11-23 23:26:19 +00:00
that.el.on('keydown.autocomplete', function (e) { that.onKeyPress(e); });
2013-04-24 20:57:23 +00:00
that.el.on('keyup.autocomplete', function (e) { that.onKeyUp(e); });
that.el.on('blur.autocomplete', function () { that.onBlur(); });
2013-11-23 23:26:19 +00:00
that.el.on('focus.autocomplete', function () { that.onFocus(); });
that.el.on('change.autocomplete', function (e) { that.onKeyUp(e); });
2014-12-03 20:23:24 +00:00
that.el.on('input.autocomplete', function (e) { that.onKeyUp(e); });
2013-11-23 23:26:19 +00:00
},
onFocus: function () {
var that = this;
2016-06-14 21:17:00 +00:00
2013-11-23 23:26:19 +00:00
that.fixPosition();
2016-06-14 21:17:00 +00:00
if (that.el.val().length >= that.options.minChars) {
2013-11-23 23:26:19 +00:00
that.onValueChange();
}
},
onBlur: function () {
this.enableKillerFn();
},
2015-05-04 00:04:25 +00:00
abortAjax: function () {
var that = this;
if (that.currentRequest) {
that.currentRequest.abort();
that.currentRequest = null;
}
},
setOptions: function (suppliedOptions) {
2013-01-15 18:25:11 +00:00
var that = this,
options = that.options;
2013-11-23 23:26:19 +00:00
$.extend(options, suppliedOptions);
2013-01-15 18:25:11 +00:00
that.isLocal = $.isArray(options.lookup);
2013-01-15 18:25:11 +00:00
if (that.isLocal) {
options.lookup = that.verifySuggestionsFormat(options.lookup);
}
2014-08-18 13:57:03 +00:00
options.orientation = that.validateOrientation(options.orientation, 'bottom');
// Adjust height, width and z-index:
2013-01-15 18:25:11 +00:00
$(that.suggestionsContainer).css({
'max-height': options.maxHeight + 'px',
2012-12-19 20:44:48 +00:00
'width': options.width + 'px',
'z-index': options.zIndex
});
},
2014-08-18 13:57:03 +00:00
clearCache: function () {
2013-11-24 16:21:19 +00:00
this.cachedResponse = {};
this.badQueries = [];
},
2013-04-24 20:57:23 +00:00
clear: function () {
this.clearCache();
2013-11-23 23:26:19 +00:00
this.currentValue = '';
2013-04-24 20:57:23 +00:00
this.suggestions = [];
},
disable: function () {
2013-11-23 23:26:19 +00:00
var that = this;
that.disabled = true;
2014-09-21 23:09:53 +00:00
clearInterval(that.onChangeInterval);
2015-05-04 00:04:25 +00:00
that.abortAjax();
},
enable: function () {
this.disabled = false;
},
fixPosition: function () {
2014-08-18 13:57:03 +00:00
// Use only when container has already its content
2013-01-21 00:53:04 +00:00
2014-08-18 13:57:03 +00:00
var that = this,
$container = $(that.suggestionsContainer),
containerParent = $container.parent().get(0);
// Fix position automatically when appended to body.
// In other cases force parameter must be given.
2014-11-25 01:41:25 +00:00
if (containerParent !== document.body && !that.options.forceFixPosition) {
2013-01-21 00:53:04 +00:00
return;
2014-11-25 01:41:25 +00:00
}
2014-08-18 13:57:03 +00:00
// Choose orientation
var orientation = that.options.orientation,
containerHeight = $container.outerHeight(),
height = that.el.outerHeight(),
offset = that.el.offset(),
styles = { 'top': offset.top, 'left': offset.left };
2014-11-25 01:41:25 +00:00
if (orientation === 'auto') {
2014-08-18 13:57:03 +00:00
var viewPortHeight = $(window).height(),
scrollTop = $(window).scrollTop(),
topOverflow = -scrollTop + offset.top - containerHeight,
bottomOverflow = scrollTop + viewPortHeight - (offset.top + height + containerHeight);
2014-08-18 13:57:03 +00:00
orientation = (Math.max(topOverflow, bottomOverflow) === topOverflow) ? 'top' : 'bottom';
2013-01-21 00:53:04 +00:00
}
if (orientation === 'top') {
2014-08-18 13:57:03 +00:00
styles.top += -containerHeight;
} else {
2014-08-18 13:57:03 +00:00
styles.top += height;
}
2013-03-27 19:01:24 +00:00
2014-08-18 13:57:03 +00:00
// If container is not positioned to body,
// correct its position using offset parent offset
if(containerParent !== document.body) {
var opacity = $container.css('opacity'),
parentOffsetDiff;
if (!that.visible){
$container.css('opacity', 0).show();
}
2014-08-18 13:57:03 +00:00
parentOffsetDiff = $container.offsetParent().offset();
styles.top -= parentOffsetDiff.top;
styles.left -= parentOffsetDiff.left;
if (!that.visible){
2014-08-18 13:57:03 +00:00
$container.css('opacity', opacity).hide();
}
2014-08-18 13:57:03 +00:00
}
2013-11-23 23:26:19 +00:00
if (that.options.width === 'auto') {
styles.width = that.el.outerWidth() + 'px';
2013-11-23 23:26:19 +00:00
}
2014-08-18 13:57:03 +00:00
$container.css(styles);
},
enableKillerFn: function () {
var that = this;
2013-04-24 20:57:23 +00:00
$(document).on('click.autocomplete', that.killerFn);
},
disableKillerFn: function () {
var that = this;
2013-04-24 20:57:23 +00:00
$(document).off('click.autocomplete', that.killerFn);
},
killSuggestions: function () {
var that = this;
that.stopKillSuggestions();
that.intervalId = window.setInterval(function () {
2015-09-16 15:49:49 +00:00
if (that.visible) {
that.el.val(that.currentValue);
that.hide();
}
that.stopKillSuggestions();
2013-11-23 23:26:19 +00:00
}, 50);
},
stopKillSuggestions: function () {
window.clearInterval(this.intervalId);
},
2013-11-23 23:26:19 +00:00
isCursorAtEnd: function () {
var that = this,
valLength = that.el.val().length,
selectionStart = that.element.selectionStart,
range;
if (typeof selectionStart === 'number') {
return selectionStart === valLength;
}
if (document.selection) {
range = document.selection.createRange();
range.moveStart('character', -valLength);
return valLength === range.text.length;
}
return true;
},
onKeyPress: function (e) {
2013-01-15 18:25:11 +00:00
var that = this;
// If suggestions are hidden and user presses arrow down, display suggestions:
2013-11-23 23:26:19 +00:00
if (!that.disabled && !that.visible && e.which === keys.DOWN && that.currentValue) {
2013-01-15 18:25:11 +00:00
that.suggest();
return;
}
2013-01-15 18:25:11 +00:00
if (that.disabled || !that.visible) {
return;
}
2013-11-23 23:26:19 +00:00
switch (e.which) {
2013-01-15 18:25:11 +00:00
case keys.ESC:
that.el.val(that.currentValue);
that.hide();
break;
2013-11-23 23:26:19 +00:00
case keys.RIGHT:
if (that.hint && that.options.onHint && that.isCursorAtEnd()) {
that.selectHint();
break;
}
return;
2013-01-15 18:25:11 +00:00
case keys.TAB:
2013-11-23 23:26:19 +00:00
if (that.hint && that.options.onHint) {
that.selectHint();
return;
}
2013-01-15 18:25:11 +00:00
if (that.selectedIndex === -1) {
that.hide();
return;
}
2013-11-23 23:26:19 +00:00
that.select(that.selectedIndex);
2014-11-25 01:41:25 +00:00
if (that.options.tabDisabled === false) {
return;
}
break;
2014-11-25 01:41:25 +00:00
case keys.RETURN:
if (that.selectedIndex === -1) {
that.hide();
return;
}
that.select(that.selectedIndex);
break;
2013-01-15 18:25:11 +00:00
case keys.UP:
that.moveUp();
break;
2013-01-15 18:25:11 +00:00
case keys.DOWN:
that.moveDown();
break;
default:
return;
}
// Cancel event if function did not return:
e.stopImmediatePropagation();
e.preventDefault();
},
onKeyUp: function (e) {
2013-01-15 18:25:11 +00:00
var that = this;
if (that.disabled) {
return;
}
2013-11-23 23:26:19 +00:00
switch (e.which) {
2013-01-15 18:25:11 +00:00
case keys.UP:
case keys.DOWN:
return;
}
2012-12-19 20:44:48 +00:00
clearInterval(that.onChangeInterval);
2012-12-19 20:44:48 +00:00
if (that.currentValue !== that.el.val()) {
2013-11-23 23:26:19 +00:00
that.findBestHint();
2012-12-19 20:44:48 +00:00
if (that.options.deferRequestBy > 0) {
// Defer lookup in case when value changes very quickly:
2012-12-19 20:44:48 +00:00
that.onChangeInterval = setInterval(function () {
that.onValueChange();
}, that.options.deferRequestBy);
} else {
2012-12-19 20:44:48 +00:00
that.onValueChange();
}
}
},
onValueChange: function () {
2013-01-15 18:25:11 +00:00
var that = this,
2013-11-24 16:21:19 +00:00
options = that.options,
value = that.el.val(),
2015-05-16 17:17:57 +00:00
query = that.getQuery(value);
2013-01-15 18:25:11 +00:00
if (that.selection && that.currentValue !== query) {
2013-11-23 23:26:19 +00:00
that.selection = null;
2013-11-24 16:21:19 +00:00
(options.onInvalidateSelection || $.noop).call(that.element);
2013-11-23 23:26:19 +00:00
}
2013-01-15 18:25:11 +00:00
clearInterval(that.onChangeInterval);
2013-11-24 16:21:19 +00:00
that.currentValue = value;
2013-01-15 18:25:11 +00:00
that.selectedIndex = -1;
2013-11-24 16:21:19 +00:00
// Check existing suggestion for the match before proceeding:
2015-05-16 17:17:57 +00:00
if (options.triggerSelectOnValidInput && that.isExactMatch(query)) {
that.select(0);
return;
2013-11-24 16:21:19 +00:00
}
if (query.length < options.minChars) {
2013-01-15 18:25:11 +00:00
that.hide();
} else {
2013-11-24 16:21:19 +00:00
that.getSuggestions(query);
}
},
2015-05-16 17:17:57 +00:00
isExactMatch: function (query) {
var suggestions = this.suggestions;
2013-11-24 16:21:19 +00:00
2015-05-16 17:17:57 +00:00
return (suggestions.length === 1 && suggestions[0].value.toLowerCase() === query.toLowerCase());
2013-11-24 16:21:19 +00:00
},
getQuery: function (value) {
var delimiter = this.options.delimiter,
parts;
if (!delimiter) {
2013-11-24 16:21:19 +00:00
return value;
}
parts = value.split(delimiter);
return $.trim(parts[parts.length - 1]);
},
2013-01-15 18:25:11 +00:00
getSuggestionsLocal: function (query) {
var that = this,
2013-11-24 16:21:19 +00:00
options = that.options,
2013-01-15 18:25:11 +00:00
queryLowerCase = query.toLowerCase(),
2013-11-24 16:21:19 +00:00
filter = options.lookupFilter,
limit = parseInt(options.lookupLimit, 10),
data;
2013-11-24 16:21:19 +00:00
data = {
suggestions: $.grep(options.lookup, function (suggestion) {
2013-01-15 18:25:11 +00:00
return filter(suggestion, query, queryLowerCase);
})
};
2013-11-24 16:21:19 +00:00
if (limit && data.suggestions.length > limit) {
data.suggestions = data.suggestions.slice(0, limit);
}
return data;
},
getSuggestions: function (q) {
var response,
that = this,
2013-04-24 21:08:01 +00:00
options = that.options,
2013-11-24 16:21:19 +00:00
serviceUrl = options.serviceUrl,
2014-08-18 13:57:03 +00:00
params,
cacheKey,
ajaxSettings;
2013-11-24 16:21:19 +00:00
options.params[options.paramName] = q;
2014-08-18 13:57:03 +00:00
params = options.ignoreParams ? null : options.params;
2013-11-24 16:21:19 +00:00
2014-09-21 23:09:53 +00:00
if (options.onSearchStart.call(that.element, options.params) === false) {
return;
}
2014-11-25 01:41:25 +00:00
if ($.isFunction(options.lookup)){
options.lookup(q, function (data) {
that.suggestions = data.suggestions;
that.suggest();
options.onSearchComplete.call(that.element, q, data.suggestions);
});
return;
}
2013-11-24 16:21:19 +00:00
if (that.isLocal) {
response = that.getSuggestionsLocal(q);
} else {
if ($.isFunction(serviceUrl)) {
serviceUrl = serviceUrl.call(that.element, q);
}
2014-08-18 13:57:03 +00:00
cacheKey = serviceUrl + '?' + $.param(params || {});
2013-11-24 16:21:19 +00:00
response = that.cachedResponse[cacheKey];
}
if (response && $.isArray(response.suggestions)) {
that.suggestions = response.suggestions;
that.suggest();
2014-09-21 23:09:53 +00:00
options.onSearchComplete.call(that.element, q, response.suggestions);
} else if (!that.isBadQuery(q)) {
2015-05-04 00:04:25 +00:00
that.abortAjax();
ajaxSettings = {
2013-04-24 21:08:01 +00:00
url: serviceUrl,
2014-08-18 13:57:03 +00:00
data: params,
type: options.type,
2013-02-08 20:51:45 +00:00
dataType: options.dataType
};
$.extend(ajaxSettings, options.ajaxSettings);
that.currentRequest = $.ajax(ajaxSettings).done(function (data) {
2014-08-18 13:57:03 +00:00
var result;
2013-11-23 23:26:19 +00:00
that.currentRequest = null;
2015-06-04 17:59:30 +00:00
result = options.transformResult(data, q);
2014-08-18 13:57:03 +00:00
that.processResponse(result, q, cacheKey);
options.onSearchComplete.call(that.element, q, result.suggestions);
2013-11-23 23:26:19 +00:00
}).fail(function (jqXHR, textStatus, errorThrown) {
options.onSearchError.call(that.element, q, jqXHR, textStatus, errorThrown);
});
2014-09-21 23:09:53 +00:00
} else {
options.onSearchComplete.call(that.element, q, []);
}
},
isBadQuery: function (q) {
2014-08-18 13:57:03 +00:00
if (!this.options.preventBadQueries){
return false;
}
var badQueries = this.badQueries,
i = badQueries.length;
while (i--) {
if (q.indexOf(badQueries[i]) === 0) {
return true;
}
}
return false;
},
hide: function () {
2015-03-04 16:52:04 +00:00
var that = this,
container = $(that.suggestionsContainer);
if ($.isFunction(that.options.onHide) && that.visible) {
that.options.onHide.call(that.element, container);
}
2013-01-15 18:25:11 +00:00
that.visible = false;
that.selectedIndex = -1;
2014-09-21 23:09:53 +00:00
clearInterval(that.onChangeInterval);
2013-01-15 18:25:11 +00:00
$(that.suggestionsContainer).hide();
2013-11-23 23:26:19 +00:00
that.signalHint(null);
},
suggest: function () {
if (this.suggestions.length === 0) {
2015-03-04 16:52:04 +00:00
if (this.options.showNoSuggestionNotice) {
this.noSuggestions();
} else {
this.hide();
}
return;
}
2013-01-15 18:25:11 +00:00
var that = this,
2013-11-24 16:21:19 +00:00
options = that.options,
2014-09-22 03:18:09 +00:00
groupBy = options.groupBy,
2013-11-24 16:21:19 +00:00
formatResult = options.formatResult,
2013-01-15 18:25:11 +00:00
value = that.getQuery(that.currentValue),
className = that.classes.suggestion,
classSelected = that.classes.selected,
container = $(that.suggestionsContainer),
2014-08-18 13:57:03 +00:00
noSuggestionsContainer = $(that.noSuggestionsContainer),
2013-11-24 16:21:19 +00:00
beforeRender = options.beforeRender,
2013-11-23 23:26:19 +00:00
html = '',
2014-09-22 03:18:09 +00:00
category,
formatGroup = function (suggestion, index) {
var currentCategory = suggestion.data[groupBy];
if (category === currentCategory){
return '';
}
category = currentCategory;
return '<div class="autocomplete-group"><strong>' + category + '</strong></div>';
2015-05-16 17:17:57 +00:00
};
2015-05-16 17:17:57 +00:00
if (options.triggerSelectOnValidInput && that.isExactMatch(value)) {
that.select(0);
return;
2013-11-24 16:21:19 +00:00
}
// Build suggestions inner HTML:
2013-01-15 18:25:11 +00:00
$.each(that.suggestions, function (i, suggestion) {
2014-09-22 03:18:09 +00:00
if (groupBy){
html += formatGroup(suggestion, value, i);
}
2016-06-14 21:17:00 +00:00
html += '<div class="' + className + '" data-index="' + i + '">' + formatResult(suggestion, value, i) + '</div>';
2012-12-19 20:44:48 +00:00
});
2014-12-03 20:23:24 +00:00
this.adjustContainerWidth();
2013-11-23 23:26:19 +00:00
2014-08-18 13:57:03 +00:00
noSuggestionsContainer.detach();
2013-11-23 23:26:19 +00:00
container.html(html);
2013-11-23 23:26:19 +00:00
if ($.isFunction(beforeRender)) {
2016-06-14 21:17:00 +00:00
beforeRender.call(that.element, container, that.suggestions);
2013-11-23 23:26:19 +00:00
}
2014-08-18 13:57:03 +00:00
that.fixPosition();
2013-11-23 23:26:19 +00:00
container.show();
// Select first value by default:
if (options.autoSelectFirst) {
that.selectedIndex = 0;
container.scrollTop(0);
2015-03-13 16:17:12 +00:00
container.children('.' + className).first().addClass(classSelected);
}
that.visible = true;
2013-11-23 23:26:19 +00:00
that.findBestHint();
},
2014-08-18 13:57:03 +00:00
noSuggestions: function() {
var that = this,
container = $(that.suggestionsContainer),
noSuggestionsContainer = $(that.noSuggestionsContainer);
this.adjustContainerWidth();
// Some explicit steps. Be careful here as it easy to get
// noSuggestionsContainer removed from DOM if not detached properly.
noSuggestionsContainer.detach();
container.empty(); // clean suggestions if any
container.append(noSuggestionsContainer);
that.fixPosition();
container.show();
that.visible = true;
},
adjustContainerWidth: function() {
var that = this,
options = that.options,
width,
container = $(that.suggestionsContainer);
// If width is auto, adjust width before displaying suggestions,
// because if instance was created before input had width, it will be zero.
// Also it adjusts if input width has changed.
// -2px to account for suggestions border.
if (options.width === 'auto') {
width = that.el.outerWidth() - 2;
container.width(width > 0 ? width : 300);
}
},
2013-11-23 23:26:19 +00:00
findBestHint: function () {
var that = this,
value = that.el.val().toLowerCase(),
bestMatch = null;
if (!value) {
return;
}
$.each(that.suggestions, function (i, suggestion) {
var foundMatch = suggestion.value.toLowerCase().indexOf(value) === 0;
if (foundMatch) {
bestMatch = suggestion;
}
return !foundMatch;
});
that.signalHint(bestMatch);
},
signalHint: function (suggestion) {
var hintValue = '',
that = this;
if (suggestion) {
hintValue = that.currentValue + suggestion.value.substr(that.currentValue.length);
}
if (that.hintValue !== hintValue) {
that.hintValue = hintValue;
that.hint = suggestion;
(this.options.onHint || $.noop)(hintValue);
}
},
2012-12-19 20:44:48 +00:00
verifySuggestionsFormat: function (suggestions) {
// If suggestions is string array, convert them to supported format:
2012-12-19 20:44:48 +00:00
if (suggestions.length && typeof suggestions[0] === 'string') {
return $.map(suggestions, function (value) {
return { value: value, data: null };
});
}
2012-12-19 20:44:48 +00:00
return suggestions;
},
2014-08-18 13:57:03 +00:00
validateOrientation: function(orientation, fallback) {
2014-08-24 23:25:55 +00:00
orientation = $.trim(orientation || '').toLowerCase();
2014-08-24 23:25:55 +00:00
if($.inArray(orientation, ['auto', 'bottom', 'top']) === -1){
2014-08-18 13:57:03 +00:00
orientation = fallback;
2014-08-24 23:25:55 +00:00
}
return orientation;
2014-08-18 13:57:03 +00:00
},
processResponse: function (result, originalQuery, cacheKey) {
2013-01-15 18:25:11 +00:00
var that = this,
2014-08-18 13:57:03 +00:00
options = that.options;
2012-12-19 20:44:48 +00:00
2013-03-27 19:01:24 +00:00
result.suggestions = that.verifySuggestionsFormat(result.suggestions);
2012-12-19 20:44:48 +00:00
// Cache results if cache is not disabled:
2013-03-27 19:01:24 +00:00
if (!options.noCache) {
2013-11-24 16:21:19 +00:00
that.cachedResponse[cacheKey] = result;
2014-08-18 13:57:03 +00:00
if (options.preventBadQueries && result.suggestions.length === 0) {
that.badQueries.push(originalQuery);
}
}
2013-11-24 16:21:19 +00:00
// Return if originalQuery is not matching current query:
if (originalQuery !== that.getQuery(that.currentValue)) {
return;
}
2013-11-24 16:21:19 +00:00
that.suggestions = result.suggestions;
that.suggest();
},
activate: function (index) {
2013-01-15 18:25:11 +00:00
var that = this,
activeItem,
selected = that.classes.selected,
container = $(that.suggestionsContainer),
children = container.find('.' + that.classes.suggestion);
container.find('.' + selected).removeClass(selected);
2013-01-15 18:25:11 +00:00
that.selectedIndex = index;
2013-01-15 18:25:11 +00:00
if (that.selectedIndex !== -1 && children.length > that.selectedIndex) {
activeItem = children.get(that.selectedIndex);
$(activeItem).addClass(selected);
return activeItem;
}
return null;
},
2013-11-23 23:26:19 +00:00
selectHint: function () {
2013-01-15 18:25:11 +00:00
var that = this,
2013-11-23 23:26:19 +00:00
i = $.inArray(that.hint, that.suggestions);
2013-11-23 23:26:19 +00:00
that.select(i);
},
select: function (i) {
var that = this;
that.hide();
that.onSelect(i);
},
moveUp: function () {
2013-01-15 18:25:11 +00:00
var that = this;
if (that.selectedIndex === -1) {
return;
}
2013-01-15 18:25:11 +00:00
if (that.selectedIndex === 0) {
$(that.suggestionsContainer).children().first().removeClass(that.classes.selected);
that.selectedIndex = -1;
that.el.val(that.currentValue);
2013-11-23 23:26:19 +00:00
that.findBestHint();
return;
}
2013-01-15 18:25:11 +00:00
that.adjustScroll(that.selectedIndex - 1);
},
moveDown: function () {
2013-01-15 18:25:11 +00:00
var that = this;
if (that.selectedIndex === (that.suggestions.length - 1)) {
return;
}
2013-01-15 18:25:11 +00:00
that.adjustScroll(that.selectedIndex + 1);
},
adjustScroll: function (index) {
2013-01-15 18:25:11 +00:00
var that = this,
activeItem = that.activate(index);
if (!activeItem) {
return;
}
var offsetTop,
upperBound,
lowerBound,
heightDelta = $(activeItem).outerHeight();
offsetTop = activeItem.offsetTop;
2013-01-15 18:25:11 +00:00
upperBound = $(that.suggestionsContainer).scrollTop();
lowerBound = upperBound + that.options.maxHeight - heightDelta;
if (offsetTop < upperBound) {
2013-01-15 18:25:11 +00:00
$(that.suggestionsContainer).scrollTop(offsetTop);
} else if (offsetTop > lowerBound) {
2013-01-15 18:25:11 +00:00
$(that.suggestionsContainer).scrollTop(offsetTop - that.options.maxHeight + heightDelta);
}
2014-12-03 20:23:24 +00:00
if (!that.options.preserveInput) {
that.el.val(that.getValue(that.suggestions[index].value));
}
2013-11-23 23:26:19 +00:00
that.signalHint(null);
},
onSelect: function (index) {
var that = this,
onSelectCallback = that.options.onSelect,
suggestion = that.suggestions[index];
2013-11-23 23:26:19 +00:00
that.currentValue = that.getValue(suggestion.value);
2014-08-18 13:57:03 +00:00
2014-12-03 20:23:24 +00:00
if (that.currentValue !== that.el.val() && !that.options.preserveInput) {
2014-08-18 13:57:03 +00:00
that.el.val(that.currentValue);
}
2013-11-23 23:26:19 +00:00
that.signalHint(null);
that.suggestions = [];
that.selection = suggestion;
if ($.isFunction(onSelectCallback)) {
onSelectCallback.call(that.element, suggestion);
}
},
getValue: function (value) {
var that = this,
delimiter = that.options.delimiter,
currentValue,
parts;
if (!delimiter) {
return value;
}
currentValue = that.currentValue;
parts = currentValue.split(delimiter);
if (parts.length === 1) {
return value;
}
return currentValue.substr(0, currentValue.length - parts[parts.length - 1].length) + value;
2013-04-24 20:57:23 +00:00
},
dispose: function () {
var that = this;
that.el.off('.autocomplete').removeData('autocomplete');
that.disableKillerFn();
2013-11-23 23:26:19 +00:00
$(window).off('resize.autocomplete', that.fixPositionCapture);
2013-04-24 20:57:23 +00:00
$(that.suggestionsContainer).remove();
}
};
// Create chainable jQuery plugin:
$.fn.autocomplete = $.fn.devbridgeAutocomplete = function (options, args) {
2013-04-24 20:57:23 +00:00
var dataKey = 'autocomplete';
// If function invoked without argument return
// instance of the first matched element:
if (arguments.length === 0) {
return this.first().data(dataKey);
}
return this.each(function () {
2013-04-24 20:57:23 +00:00
var inputElement = $(this),
instance = inputElement.data(dataKey);
if (typeof options === 'string') {
2013-04-24 20:57:23 +00:00
if (instance && typeof instance[options] === 'function') {
instance[options](args);
}
} else {
2013-04-24 20:57:23 +00:00
// If instance already exists, destroy it:
if (instance && instance.dispose) {
instance.dispose();
}
instance = new Autocomplete(this, options);
inputElement.data(dataKey, instance);
}
});
};
2013-04-24 20:57:23 +00:00
}));