2 * jQuery Autocomplete plugin 1.1
4 * Copyright (c) 2009 Jörn Zaefferer
6 * Dual licensed under the MIT and GPL licenses:
7 * http://www.opensource.org/licenses/mit-license.php
8 * http://www.gnu.org/licenses/gpl.html
10 * Revision: $Id: jquery.autocomplete.js 15 2009-08-22 10:30:27Z joern.zaefferer $
12 * changed by Radek Czajka (FNP), 20100907: ignore alt keydown
18 autocomplete: function(urlOrData, options) {
19 var isUrl = typeof urlOrData == "string";
20 options = $.extend({}, $.Autocompleter.defaults, {
21 url: isUrl ? urlOrData : null,
22 data: isUrl ? null : urlOrData,
23 delay: isUrl ? $.Autocompleter.defaults.delay : 10,
24 max: options && !options.scroll ? 10 : 150
27 // if highlight is set to false, replace it with a do-nothing function
28 options.highlight = options.highlight || function(value) { return value; };
30 // if the formatMatch option is not specified, then use formatItem for backwards compatibility
31 options.formatMatch = options.formatMatch || options.formatItem;
33 return this.each(function() {
34 new $.Autocompleter(this, options);
37 result: function(handler) {
38 return this.bind("result", handler);
40 search: function(handler) {
41 return this.trigger("search", [handler]);
43 flushCache: function() {
44 return this.trigger("flushCache");
46 setOptions: function(options){
47 return this.trigger("setOptions", [options]);
49 unautocomplete: function() {
50 return this.trigger("unautocomplete");
54 $.Autocompleter = function(input, options) {
69 // Create $ object for input element
70 var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);
73 var previousValue = "";
74 var cache = $.Autocompleter.Cache(options);
78 mouseDownOnSelect: false
80 var select = $.Autocompleter.Select(options, input, selectCurrent, config);
84 // prevent form submit in opera when selecting with return key
85 $.browser.opera && $(input.form).bind("submit.autocomplete", function() {
92 // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
93 $input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
94 // a keypress means the input has focus
95 // avoids issue where input had focus before the autocomplete was applied
97 // track last key pressed
98 lastKeyPressCode = event.keyCode;
99 switch(event.keyCode) {
108 event.preventDefault();
109 if ( select.visible() ) {
117 event.preventDefault();
118 if ( select.visible() ) {
126 event.preventDefault();
127 if ( select.visible() ) {
135 event.preventDefault();
136 if ( select.visible() ) {
143 // matches also semicolon
144 case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
147 if( selectCurrent() ) {
148 // stop default to prevent a form submit, Opera needs special handling
149 event.preventDefault();
160 clearTimeout(timeout);
161 timeout = setTimeout(onChange, options.delay);
165 // track whether the field has focus, we shouldn't process any
166 // results if the field no longer has focus
170 if (!config.mouseDownOnSelect) {
173 }).click(function() {
174 // show select when clicking in a focused field
175 if ( hasFocus++ > 1 && !select.visible() ) {
178 }).bind("search", function() {
179 // TODO why not just specifying both arguments?
180 var fn = (arguments.length > 1) ? arguments[1] : null;
181 function findValueCallback(q, data) {
183 if( data && data.length ) {
184 for (var i=0; i < data.length; i++) {
185 if( data[i].result.toLowerCase() == q.toLowerCase() ) {
191 if( typeof fn == "function" ) fn(result);
192 else $input.trigger("result", result && [result.data, result.value]);
194 $.each(trimWords($input.val()), function(i, value) {
195 request(value, findValueCallback, findValueCallback);
197 }).bind("flushCache", function() {
199 }).bind("setOptions", function() {
200 $.extend(options, arguments[1]);
201 // if we've updated the data, repopulate
202 if ( "data" in arguments[1] )
204 }).bind("unautocomplete", function() {
207 $(input.form).unbind(".autocomplete");
211 function selectCurrent() {
212 var selected = select.selected();
216 var v = selected.result;
219 if ( options.multiple ) {
220 var words = trimWords($input.val());
221 if ( words.length > 1 ) {
222 var seperator = options.multipleSeparator.length;
223 var cursorAt = $(input).selection().start;
224 var wordAt, progress = 0;
225 $.each(words, function(i, word) {
226 progress += word.length;
227 if (cursorAt <= progress) {
231 progress += seperator;
234 // TODO this should set the cursor to the right position, but it gets overriden somewhere
235 //$.Autocompleter.Selection(input, progress + seperator, progress + seperator);
236 v = words.join( options.multipleSeparator );
238 v += options.multipleSeparator;
243 $input.trigger("result", [selected.data, selected.value]);
247 function onChange(crap, skipPrevCheck) {
248 if( lastKeyPressCode == KEY.DEL ) {
253 var currentValue = $input.val();
255 if ( !skipPrevCheck && currentValue == previousValue )
258 previousValue = currentValue;
260 currentValue = lastWord(currentValue);
261 if ( currentValue.length >= options.minChars) {
262 $input.addClass(options.loadingClass);
263 if (!options.matchCase)
264 currentValue = currentValue.toLowerCase();
265 request(currentValue, receiveData, hideResultsNow);
272 function trimWords(value) {
275 if (!options.multiple)
276 return [$.trim(value)];
277 return $.map(value.split(options.multipleSeparator), function(word) {
278 return $.trim(value).length ? $.trim(word) : null;
282 function lastWord(value) {
283 if ( !options.multiple )
285 var words = trimWords(value);
286 if (words.length == 1)
288 var cursorAt = $(input).selection().start;
289 if (cursorAt == value.length) {
290 words = trimWords(value)
292 words = trimWords(value.replace(value.substring(cursorAt), ""));
294 return words[words.length - 1];
297 // fills in the input box w/the first match (assumed to be the best match)
298 // q: the term entered
299 // sValue: the first matching result
300 function autoFill(q, sValue){
301 // autofill in the complete box w/the first match as long as the user hasn't entered in more data
302 // if the last user key pressed was backspace, don't autofill
303 if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {
304 // fill in the value (keep the case the user has typed)
305 $input.val($input.val() + sValue.substring(lastWord(previousValue).length));
306 // select the portion of the value not typed by the user (so the next character will erase)
307 $(input).selection(previousValue.length, previousValue.length + sValue.length);
311 function hideResults() {
312 clearTimeout(timeout);
313 timeout = setTimeout(hideResultsNow, 200);
316 function hideResultsNow() {
317 var wasVisible = select.visible();
319 clearTimeout(timeout);
321 if (options.mustMatch) {
322 // call search and run callback
325 // if no value found, clear the input box
327 if (options.multiple) {
328 var words = trimWords($input.val()).slice(0, -1);
329 $input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
333 $input.trigger("result", null);
341 function receiveData(q, data) {
342 if ( data && data.length && hasFocus ) {
344 select.display(data, q);
345 autoFill(q, data[0].value);
352 function request(term, success, failure) {
353 if (!options.matchCase)
354 term = term.toLowerCase();
355 var data = cache.load(term);
356 // recieve the cached data
357 if (data && data.length) {
359 // if an AJAX url has been supplied, try loading the data now
360 } else if( (typeof options.url == "string") && (options.url.length > 0) ){
363 timestamp: +new Date()
365 $.each(options.extraParams, function(key, param) {
366 extraParams[key] = typeof param == "function" ? param() : param;
370 // try to leverage ajaxQueue plugin to abort previous requests
372 // limit abortion to this input
373 port: "autocomplete" + input.name,
374 dataType: options.dataType,
380 success: function(data) {
381 var parsed = options.parse && options.parse(data) || parse(data);
382 cache.add(term, parsed);
383 success(term, parsed);
387 // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
393 function parse(data) {
395 var rows = data.split("\n");
396 for (var i=0; i < rows.length; i++) {
397 var row = $.trim(rows[i]);
399 row = row.split("|");
400 parsed[parsed.length] = {
403 result: options.formatResult && options.formatResult(row, row[0]) || row[0]
410 function stopLoading() {
411 $input.removeClass(options.loadingClass);
416 $.Autocompleter.defaults = {
417 inputClass: "ac_input",
418 resultsClass: "ac_results",
419 loadingClass: "ac_loading",
424 matchContains: false,
430 formatItem: function(row) { return row[0]; },
435 multipleSeparator: ", ",
436 highlight: function(value, term) {
437 return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
443 $.Autocompleter.Cache = function(options) {
448 function matchSubset(s, sub) {
449 if (!options.matchCase)
451 var i = s.indexOf(sub);
452 if (options.matchContains == "word"){
453 i = s.toLowerCase().search("\\b" + sub.toLowerCase());
455 if (i == -1) return false;
456 return i == 0 || options.matchContains;
459 function add(q, value) {
460 if (length > options.cacheLength){
470 if( !options.data ) return false;
472 var stMatchSets = {},
475 // no url was specified, we need to adjust the cache length to make sure it fits the local data store
476 if( !options.url ) options.cacheLength = 1;
478 // track all options for minChars = 0
479 stMatchSets[""] = [];
481 // loop through the array and create a lookup structure
482 for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
483 var rawValue = options.data[i];
484 // if rawValue is a string, make an array otherwise just reference the array
485 rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;
487 var value = options.formatMatch(rawValue, i+1, options.data.length);
488 if ( value === false )
491 var firstChar = value.charAt(0).toLowerCase();
492 // if no lookup array for this character exists, look it up now
493 if( !stMatchSets[firstChar] )
494 stMatchSets[firstChar] = [];
496 // if the match is a string
500 result: options.formatResult && options.formatResult(rawValue) || value
503 // push the current match into the set list
504 stMatchSets[firstChar].push(row);
506 // keep track of minChars zero items
507 if ( nullData++ < options.max ) {
508 stMatchSets[""].push(row);
512 // add the data items to the cache
513 $.each(stMatchSets, function(i, value) {
514 // increase the cache size
515 options.cacheLength++;
521 // populate any existing data
522 setTimeout(populate, 25);
534 if (!options.cacheLength || !length)
537 * if dealing w/local data and matchContains than we must make sure
538 * to loop through all the data collections looking for matches
540 if( !options.url && options.matchContains ){
543 // loop through all the data grids for matches
544 for( var k in data ){
545 // don't search through the stMatchSets[""] (minChars: 0) cache
546 // this prevents duplicates
549 $.each(c, function(i, x) {
550 // if we've got a match, add it to the array
551 if (matchSubset(x.value, q)) {
559 // if the exact item exists, use it
563 if (options.matchSubset) {
564 for (var i = q.length - 1; i >= options.minChars; i--) {
565 var c = data[q.substr(0, i)];
568 $.each(c, function(i, x) {
569 if (matchSubset(x.value, q)) {
570 csub[csub.length] = x;
582 $.Autocompleter.Select = function (options, input, select, config) {
599 element = $("<div/>")
601 .addClass(options.resultsClass)
602 .css("position", "absolute")
603 .appendTo(document.body);
605 list = $("<ul/>").appendTo(element).mouseover( function(event) {
606 if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
607 active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
608 $(target(event)).addClass(CLASSES.ACTIVE);
610 }).click(function(event) {
611 $(target(event)).addClass(CLASSES.ACTIVE);
613 // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
616 }).mousedown(function() {
617 config.mouseDownOnSelect = true;
618 }).mouseup(function() {
619 config.mouseDownOnSelect = false;
622 if( options.width > 0 )
623 element.css("width", options.width);
628 function target(event) {
629 var element = event.target;
630 while(element && element.tagName != "LI")
631 element = element.parentNode;
632 // more fun with IE, sometimes event.target is empty, just ignore it then
638 function moveSelect(step) {
639 listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
641 var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
644 listItems.slice(0, active).each(function() {
645 offset += this.offsetHeight;
647 if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
648 list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
649 } else if(offset < list.scrollTop()) {
650 list.scrollTop(offset);
655 function movePosition(step) {
658 active = listItems.size() - 1;
659 } else if (active >= listItems.size()) {
664 function limitNumberOfItems(available) {
665 return options.max && options.max < available
670 function fillList() {
672 var max = limitNumberOfItems(data.length);
673 for (var i=0; i < max; i++) {
676 var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
677 if ( formatted === false )
679 var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
680 $.data(li, "ac_data", data[i]);
682 listItems = list.find("li");
683 if ( options.selectFirst ) {
684 listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
687 // apply bgiframe if available
693 display: function(d, q) {
706 if (active != 0 && active - 8 < 0) {
707 moveSelect( -active );
712 pageDown: function() {
713 if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
714 moveSelect( listItems.size() - 1 - active );
720 element && element.hide();
721 listItems && listItems.removeClass(CLASSES.ACTIVE);
724 visible : function() {
725 return element && element.is(":visible");
727 current: function() {
728 return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
731 var offset = $(input).offset();
733 width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
734 top: offset.top + input.offsetHeight,
740 maxHeight: options.scrollHeight,
744 if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
746 listItems.each(function() {
747 listHeight += this.offsetHeight;
749 var scrollbarsVisible = listHeight > options.scrollHeight;
750 list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
751 if (!scrollbarsVisible) {
752 // IE doesn't recalculate width when scrollbar disappears
753 listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
759 selected: function() {
760 var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
761 return selected && selected.length && $.data(selected[0], "ac_data");
763 emptyList: function (){
764 list && list.empty();
767 element && element.remove();
772 $.fn.selection = function(start, end) {
773 if (start !== undefined) {
774 return this.each(function() {
775 if( this.createTextRange ){
776 var selRange = this.createTextRange();
777 if (end === undefined || start == end) {
778 selRange.move("character", start);
781 selRange.collapse(true);
782 selRange.moveStart("character", start);
783 selRange.moveEnd("character", end);
786 } else if( this.setSelectionRange ){
787 this.setSelectionRange(start, end);
788 } else if( this.selectionStart ){
789 this.selectionStart = start;
790 this.selectionEnd = end;
795 if ( field.createTextRange ) {
796 var range = document.selection.createRange(),
799 textLength = range.text.length;
800 range.text = teststring;
801 var caretAt = field.value.indexOf(teststring);
803 this.selection(caretAt, caretAt + textLength);
806 end: caretAt + textLength
808 } else if( field.selectionStart !== undefined ){
810 start: field.selectionStart,
811 end: field.selectionEnd