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 $
16 autocomplete: function(urlOrData, options) {
17 var isUrl = typeof urlOrData == "string";
18 options = $.extend({}, $.Autocompleter.defaults, {
19 url: isUrl ? urlOrData : null,
20 data: isUrl ? null : urlOrData,
21 delay: isUrl ? $.Autocompleter.defaults.delay : 10,
22 max: options && !options.scroll ? 10 : 150
25 // if highlight is set to false, replace it with a do-nothing function
26 options.highlight = options.highlight || function(value) { return value; };
28 // if the formatMatch option is not specified, then use formatItem for backwards compatibility
29 options.formatMatch = options.formatMatch || options.formatItem;
31 return this.each(function() {
32 new $.Autocompleter(this, options);
35 result: function(handler) {
36 return this.bind("result", handler);
38 search: function(handler) {
39 return this.trigger("search", [handler]);
41 flushCache: function() {
42 return this.trigger("flushCache");
44 setOptions: function(options){
45 return this.trigger("setOptions", [options]);
47 unautocomplete: function() {
48 return this.trigger("unautocomplete");
52 $.Autocompleter = function(input, options) {
67 // Create $ object for input element
68 var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);
71 var previousValue = "";
72 var cache = $.Autocompleter.Cache(options);
76 mouseDownOnSelect: false
78 var select = $.Autocompleter.Select(options, input, selectCurrent, config);
82 // prevent form submit in opera when selecting with return key
83 $.browser.opera && $(input.form).bind("submit.autocomplete", function() {
90 // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
91 $input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
92 // a keypress means the input has focus
93 // avoids issue where input had focus before the autocomplete was applied
95 // track last key pressed
96 lastKeyPressCode = event.keyCode;
97 switch(event.keyCode) {
100 event.preventDefault();
101 if ( select.visible() ) {
109 event.preventDefault();
110 if ( select.visible() ) {
118 event.preventDefault();
119 if ( select.visible() ) {
127 event.preventDefault();
128 if ( select.visible() ) {
135 // matches also semicolon
136 case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
139 if( selectCurrent() ) {
140 // stop default to prevent a form submit, Opera needs special handling
141 event.preventDefault();
152 clearTimeout(timeout);
153 timeout = setTimeout(onChange, options.delay);
157 // track whether the field has focus, we shouldn't process any
158 // results if the field no longer has focus
162 if (!config.mouseDownOnSelect) {
165 }).click(function() {
166 // show select when clicking in a focused field
167 if ( hasFocus++ > 1 && !select.visible() ) {
170 }).bind("search", function() {
171 // TODO why not just specifying both arguments?
172 var fn = (arguments.length > 1) ? arguments[1] : null;
173 function findValueCallback(q, data) {
175 if( data && data.length ) {
176 for (var i=0; i < data.length; i++) {
177 if( data[i].result.toLowerCase() == q.toLowerCase() ) {
183 if( typeof fn == "function" ) fn(result);
184 else $input.trigger("result", result && [result.data, result.value]);
186 $.each(trimWords($input.val()), function(i, value) {
187 request(value, findValueCallback, findValueCallback);
189 }).bind("flushCache", function() {
191 }).bind("setOptions", function() {
192 $.extend(options, arguments[1]);
193 // if we've updated the data, repopulate
194 if ( "data" in arguments[1] )
196 }).bind("unautocomplete", function() {
199 $(input.form).unbind(".autocomplete");
203 function selectCurrent() {
204 var selected = select.selected();
208 var v = selected.result;
211 if ( options.multiple ) {
212 var words = trimWords($input.val());
213 if ( words.length > 1 ) {
214 var seperator = options.multipleSeparator.length;
215 var cursorAt = $(input).selection().start;
216 var wordAt, progress = 0;
217 $.each(words, function(i, word) {
218 progress += word.length;
219 if (cursorAt <= progress) {
223 progress += seperator;
226 // TODO this should set the cursor to the right position, but it gets overriden somewhere
227 //$.Autocompleter.Selection(input, progress + seperator, progress + seperator);
228 v = words.join( options.multipleSeparator );
230 v += options.multipleSeparator;
235 $input.trigger("result", [selected.data, selected.value]);
239 function onChange(crap, skipPrevCheck) {
240 if( lastKeyPressCode == KEY.DEL ) {
245 var currentValue = $input.val();
247 if ( !skipPrevCheck && currentValue == previousValue )
250 previousValue = currentValue;
252 currentValue = lastWord(currentValue);
253 if ( currentValue.length >= options.minChars) {
254 $input.addClass(options.loadingClass);
255 if (!options.matchCase)
256 currentValue = currentValue.toLowerCase();
257 request(currentValue, receiveData, hideResultsNow);
264 function trimWords(value) {
267 if (!options.multiple)
268 return [$.trim(value)];
269 return $.map(value.split(options.multipleSeparator), function(word) {
270 return $.trim(value).length ? $.trim(word) : null;
274 function lastWord(value) {
275 if ( !options.multiple )
277 var words = trimWords(value);
278 if (words.length == 1)
280 var cursorAt = $(input).selection().start;
281 if (cursorAt == value.length) {
282 words = trimWords(value)
284 words = trimWords(value.replace(value.substring(cursorAt), ""));
286 return words[words.length - 1];
289 // fills in the input box w/the first match (assumed to be the best match)
290 // q: the term entered
291 // sValue: the first matching result
292 function autoFill(q, sValue){
293 // autofill in the complete box w/the first match as long as the user hasn't entered in more data
294 // if the last user key pressed was backspace, don't autofill
295 if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {
296 // fill in the value (keep the case the user has typed)
297 $input.val($input.val() + sValue.substring(lastWord(previousValue).length));
298 // select the portion of the value not typed by the user (so the next character will erase)
299 $(input).selection(previousValue.length, previousValue.length + sValue.length);
303 function hideResults() {
304 clearTimeout(timeout);
305 timeout = setTimeout(hideResultsNow, 200);
308 function hideResultsNow() {
309 var wasVisible = select.visible();
311 clearTimeout(timeout);
313 if (options.mustMatch) {
314 // call search and run callback
317 // if no value found, clear the input box
319 if (options.multiple) {
320 var words = trimWords($input.val()).slice(0, -1);
321 $input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
325 $input.trigger("result", null);
333 function receiveData(q, data) {
334 if ( data && data.length && hasFocus ) {
336 select.display(data, q);
337 autoFill(q, data[0].value);
344 function request(term, success, failure) {
345 if (!options.matchCase)
346 term = term.toLowerCase();
347 var data = cache.load(term);
348 // recieve the cached data
349 if (data && data.length) {
351 // if an AJAX url has been supplied, try loading the data now
352 } else if( (typeof options.url == "string") && (options.url.length > 0) ){
355 timestamp: +new Date()
357 $.each(options.extraParams, function(key, param) {
358 extraParams[key] = typeof param == "function" ? param() : param;
362 // try to leverage ajaxQueue plugin to abort previous requests
364 // limit abortion to this input
365 port: "autocomplete" + input.name,
366 dataType: options.dataType,
372 success: function(data) {
373 var parsed = options.parse && options.parse(data) || parse(data);
374 cache.add(term, parsed);
375 success(term, parsed);
379 // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
385 function parse(data) {
387 var rows = data.split("\n");
388 for (var i=0; i < rows.length; i++) {
389 var row = $.trim(rows[i]);
391 row = row.split("|");
392 parsed[parsed.length] = {
395 result: options.formatResult && options.formatResult(row, row[0]) || row[0]
402 function stopLoading() {
403 $input.removeClass(options.loadingClass);
408 $.Autocompleter.defaults = {
409 inputClass: "ac_input",
410 resultsClass: "ac_results",
411 loadingClass: "ac_loading",
416 matchContains: false,
422 formatItem: function(row) { return row[0]; },
427 multipleSeparator: ", ",
428 highlight: function(value, term) {
429 return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
435 $.Autocompleter.Cache = function(options) {
440 function matchSubset(s, sub) {
441 if (!options.matchCase)
443 var i = s.indexOf(sub);
444 if (options.matchContains == "word"){
445 i = s.toLowerCase().search("\\b" + sub.toLowerCase());
447 if (i == -1) return false;
448 return i == 0 || options.matchContains;
451 function add(q, value) {
452 if (length > options.cacheLength){
462 if( !options.data ) return false;
464 var stMatchSets = {},
467 // no url was specified, we need to adjust the cache length to make sure it fits the local data store
468 if( !options.url ) options.cacheLength = 1;
470 // track all options for minChars = 0
471 stMatchSets[""] = [];
473 // loop through the array and create a lookup structure
474 for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
475 var rawValue = options.data[i];
476 // if rawValue is a string, make an array otherwise just reference the array
477 rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;
479 var value = options.formatMatch(rawValue, i+1, options.data.length);
480 if ( value === false )
483 var firstChar = value.charAt(0).toLowerCase();
484 // if no lookup array for this character exists, look it up now
485 if( !stMatchSets[firstChar] )
486 stMatchSets[firstChar] = [];
488 // if the match is a string
492 result: options.formatResult && options.formatResult(rawValue) || value
495 // push the current match into the set list
496 stMatchSets[firstChar].push(row);
498 // keep track of minChars zero items
499 if ( nullData++ < options.max ) {
500 stMatchSets[""].push(row);
504 // add the data items to the cache
505 $.each(stMatchSets, function(i, value) {
506 // increase the cache size
507 options.cacheLength++;
513 // populate any existing data
514 setTimeout(populate, 25);
526 if (!options.cacheLength || !length)
529 * if dealing w/local data and matchContains than we must make sure
530 * to loop through all the data collections looking for matches
532 if( !options.url && options.matchContains ){
535 // loop through all the data grids for matches
536 for( var k in data ){
537 // don't search through the stMatchSets[""] (minChars: 0) cache
538 // this prevents duplicates
541 $.each(c, function(i, x) {
542 // if we've got a match, add it to the array
543 if (matchSubset(x.value, q)) {
551 // if the exact item exists, use it
555 if (options.matchSubset) {
556 for (var i = q.length - 1; i >= options.minChars; i--) {
557 var c = data[q.substr(0, i)];
560 $.each(c, function(i, x) {
561 if (matchSubset(x.value, q)) {
562 csub[csub.length] = x;
574 $.Autocompleter.Select = function (options, input, select, config) {
591 element = $("<div/>")
593 .addClass(options.resultsClass)
594 .css("position", "absolute")
595 .appendTo(document.body);
597 list = $("<ul/>").appendTo(element).mouseover( function(event) {
598 if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
599 active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
600 $(target(event)).addClass(CLASSES.ACTIVE);
602 }).click(function(event) {
603 $(target(event)).addClass(CLASSES.ACTIVE);
605 // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
608 }).mousedown(function() {
609 config.mouseDownOnSelect = true;
610 }).mouseup(function() {
611 config.mouseDownOnSelect = false;
614 if( options.width > 0 )
615 element.css("width", options.width);
620 function target(event) {
621 var element = event.target;
622 while(element && element.tagName != "LI")
623 element = element.parentNode;
624 // more fun with IE, sometimes event.target is empty, just ignore it then
630 function moveSelect(step) {
631 listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
633 var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
636 listItems.slice(0, active).each(function() {
637 offset += this.offsetHeight;
639 if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
640 list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
641 } else if(offset < list.scrollTop()) {
642 list.scrollTop(offset);
647 function movePosition(step) {
650 active = listItems.size() - 1;
651 } else if (active >= listItems.size()) {
656 function limitNumberOfItems(available) {
657 return options.max && options.max < available
662 function fillList() {
664 var max = limitNumberOfItems(data.length);
665 for (var i=0; i < max; i++) {
668 var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
669 if ( formatted === false )
671 var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
672 $.data(li, "ac_data", data[i]);
674 listItems = list.find("li");
675 if ( options.selectFirst ) {
676 listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
679 // apply bgiframe if available
685 display: function(d, q) {
698 if (active != 0 && active - 8 < 0) {
699 moveSelect( -active );
704 pageDown: function() {
705 if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
706 moveSelect( listItems.size() - 1 - active );
712 element && element.hide();
713 listItems && listItems.removeClass(CLASSES.ACTIVE);
716 visible : function() {
717 return element && element.is(":visible");
719 current: function() {
720 return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
723 var offset = $(input).offset();
725 width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
726 top: offset.top + input.offsetHeight,
732 maxHeight: options.scrollHeight,
736 if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
738 listItems.each(function() {
739 listHeight += this.offsetHeight;
741 var scrollbarsVisible = listHeight > options.scrollHeight;
742 list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
743 if (!scrollbarsVisible) {
744 // IE doesn't recalculate width when scrollbar disappears
745 listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
751 selected: function() {
752 var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
753 return selected && selected.length && $.data(selected[0], "ac_data");
755 emptyList: function (){
756 list && list.empty();
759 element && element.remove();
764 $.fn.selection = function(start, end) {
765 if (start !== undefined) {
766 return this.each(function() {
767 if( this.createTextRange ){
768 var selRange = this.createTextRange();
769 if (end === undefined || start == end) {
770 selRange.move("character", start);
773 selRange.collapse(true);
774 selRange.moveStart("character", start);
775 selRange.moveEnd("character", end);
778 } else if( this.setSelectionRange ){
779 this.setSelectionRange(start, end);
780 } else if( this.selectionStart ){
781 this.selectionStart = start;
782 this.selectionEnd = end;
787 if ( field.createTextRange ) {
788 var range = document.selection.createRange(),
791 textLength = range.text.length;
792 range.text = teststring;
793 var caretAt = field.value.indexOf(teststring);
795 this.selection(caretAt, caretAt + textLength);
798 end: caretAt + textLength
800 } else if( field.selectionStart !== undefined ){
802 start: field.selectionStart,
803 end: field.selectionEnd