2
0
mirror of https://github.com/devbridge/jQuery-Autocomplete.git synced 2024-11-25 22:27:39 +00:00
jQuery-Autocomplete/dist/jquery.autocomplete.js

920 lines
30 KiB
JavaScript
Raw Permalink Normal View History

/**
2014-08-24 23:25:55 +00:00
* Ajax Autocomplete for jQuery, version 1.2.11
2014-08-18 13:54:08 +00:00
* (c) 2014 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
*
*/
2013-01-15 18:25:11 +00:00
/*jslint browser: true, white: true, plusplus: true */
/*global define, window, document, jQuery */
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 {
// 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 = {
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,
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) {
2013-11-23 23:26:19 +00:00
var pattern = '(' + utils.escapeRegExChars(currentValue) + ')';
return suggestion.value.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>');
};
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,
2014-08-18 13:57:03 +00:00
container,
noSuggestionsContainer;
// 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'));
});
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); });
},
onFocus: function () {
var that = this;
that.fixPosition();
if (that.options.minChars <= that.el.val().length) {
that.onValueChange();
}
},
onBlur: function () {
this.enableKillerFn();
},
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;
if (that.currentRequest) {
that.currentRequest.abort();
}
},
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.
if (containerParent !== document.body && !that.options.forceFixPosition)
2013-01-21 00:53:04 +00:00
return;
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 };
if (orientation == 'auto') {
var viewPortHeight = $(window).height(),
scrollTop = $(window).scrollTop(),
top_overflow = -scrollTop + offset.top - containerHeight,
bottom_overflow = scrollTop + viewPortHeight - (offset.top + height + containerHeight);
if (Math.max(top_overflow, bottom_overflow) === top_overflow)
orientation = 'top';
else
orientation = 'bottom';
2013-01-21 00:53:04 +00:00
}
2014-08-18 13:57:03 +00:00
if (orientation === 'top')
styles.top += -containerHeight;
else
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();
parentOffsetDiff = $container.offsetParent().offset();
styles.top -= parentOffsetDiff.top;
styles.left -= parentOffsetDiff.left;
if (!that.visible)
$container.css('opacity', opacity).hide();
}
2013-11-23 23:26:19 +00:00
2014-08-18 13:57:03 +00:00
// -2px to account for suggestions border.
2013-11-23 23:26:19 +00:00
if (that.options.width === 'auto') {
styles.width = (that.el.outerWidth() - 2) + 'px';
}
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 () {
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;
}
// Fall through to RETURN
2013-01-15 18:25:11 +00:00
case keys.RETURN:
if (that.selectedIndex === -1) {
that.hide();
return;
}
2013-11-23 23:26:19 +00:00
that.select(that.selectedIndex);
if (e.which === keys.TAB && that.options.tabDisabled === false) {
return;
}
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(),
query = that.getQuery(value),
index;
2013-01-15 18:25:11 +00:00
2013-11-23 23:26:19 +00:00
if (that.selection) {
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:
if (options.triggerSelectOnValidInput) {
index = that.findSuggestionIndex(query);
if (index !== -1) {
that.select(index);
return;
}
}
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);
}
},
2013-11-24 16:21:19 +00:00
findSuggestionIndex: function (query) {
var that = this,
index = -1,
queryLowerCase = query.toLowerCase();
$.each(that.suggestions, function (i, suggestion) {
if (suggestion.value.toLowerCase() === queryLowerCase) {
index = i;
return false;
}
});
return index;
},
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,
2013-11-24 16:21:19 +00:00
cacheKey;
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
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();
} else if (!that.isBadQuery(q)) {
2013-04-24 21:08:01 +00:00
if (options.onSearchStart.call(that.element, options.params) === false) {
return;
}
2013-11-23 23:26:19 +00:00
if (that.currentRequest) {
that.currentRequest.abort();
}
that.currentRequest = $.ajax({
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
2013-03-27 19:01:24 +00:00
}).done(function (data) {
2014-08-18 13:57:03 +00:00
var result;
2013-11-23 23:26:19 +00:00
that.currentRequest = null;
2014-08-18 13:57:03 +00:00
result = options.transformResult(data);
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);
});
}
},
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 () {
2013-01-15 18:25:11 +00:00
var that = this;
that.visible = false;
that.selectedIndex = -1;
$(that.suggestionsContainer).hide();
2013-11-23 23:26:19 +00:00
that.signalHint(null);
},
suggest: function () {
if (this.suggestions.length === 0) {
2014-08-18 13:57:03 +00:00
this.options.showNoSuggestionNotice ? this.noSuggestions() : 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,
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 = '',
2013-11-24 16:21:19 +00:00
index,
2013-11-23 23:26:19 +00:00
width;
2013-11-24 16:21:19 +00:00
if (options.triggerSelectOnValidInput) {
index = that.findSuggestionIndex(value);
if (index !== -1) {
that.select(index);
return;
}
}
// Build suggestions inner HTML:
2013-01-15 18:25:11 +00:00
$.each(that.suggestions, function (i, suggestion) {
2012-12-19 20:44:48 +00:00
html += '<div class="' + className + '" data-index="' + i + '">' + formatResult(suggestion, value) + '</div>';
});
2014-08-18 13:57:03 +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);
// Select first value by default:
2013-11-24 16:21:19 +00:00
if (options.autoSelectFirst) {
2013-01-21 00:53:04 +00:00
that.selectedIndex = 0;
container.children().first().addClass(classSelected);
}
2013-11-23 23:26:19 +00:00
if ($.isFunction(beforeRender)) {
beforeRender.call(that.element, container);
}
2014-08-18 13:57:03 +00:00
that.fixPosition();
2013-11-23 23:26:19 +00:00
container.show();
that.visible = true;
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();
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
}
2014-08-18 13:57:03 +00:00
return orientation
},
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.children();
container.children('.' + 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),
offsetTop,
upperBound,
lowerBound,
heightDelta = 25;
if (!activeItem) {
return;
}
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);
}
2013-01-15 18:25:11 +00:00
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
if (that.currentValue !== that.el.val()) {
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:
2014-08-18 13:57:03 +00:00
$.fn.autocomplete = 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
}));