2 * Autocomplete - jQuery plugin 1.0.2
4 * Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, 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 5747 2008-06-25 18:30:55Z joern.zaefferer $
17 autocomplete: function(urlOrData, options) {
18 var isUrl = typeof urlOrData == "string";
19 options = $.extend({}, $.Autocompleter.defaults, {
20 url: isUrl ? urlOrData : null,
21 data: isUrl ? null : urlOrData,
22 delay: isUrl ? $.Autocompleter.defaults.delay : 10,
23 max: options && !options.scroll ? 10 : 150
26 // if highlight is set to false, replace it with a do-nothing function
27 options.highlight = options.highlight || function(value) { return value; };
29 // if the formatMatch option is not specified, then use formatItem for backwards compatibility
30 options.formatMatch = options.formatMatch || options.formatItem;
32 return this.each(function() {
33 new $.Autocompleter(this, options);
36 result: function(handler) {
37 return this.bind("result", handler);
39 search: function(handler) {
40 return this.trigger("search", [handler]);
42 flushCache: function() {
43 return this.trigger("flushCache");
45 setOptions: function(options){
46 return this.trigger("setOptions", [options]);
48 unautocomplete: function() {
49 return this.trigger("unautocomplete");
53 $.Autocompleter = function(input, options) {
68 // Create $ object for input element
69 var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);
72 var previousValue = "";
73 var cache = $.Autocompleter.Cache(options);
77 mouseDownOnSelect: false
79 var select = $.Autocompleter.Select(options, input, selectCurrent, config);
83 // prevent form submit in opera when selecting with return key
84 $.browser.opera && $(input.form).bind("submit.autocomplete", function() {
91 // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
92 $input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
93 // track last key pressed
94 lastKeyPressCode = event.keyCode;
95 switch(event.keyCode) {
98 event.preventDefault();
99 if ( select.visible() ) {
107 event.preventDefault();
108 if ( select.visible() ) {
116 event.preventDefault();
117 if ( select.visible() ) {
125 event.preventDefault();
126 if ( select.visible() ) {
133 // matches also semicolon
134 case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
137 if( selectCurrent() ) {
138 // stop default to prevent a form submit, Opera needs special handling
139 event.preventDefault();
150 clearTimeout(timeout);
151 timeout = setTimeout(onChange, options.delay);
155 // track whether the field has focus, we shouldn't process any
156 // results if the field no longer has focus
160 if (!config.mouseDownOnSelect) {
163 }).click(function() {
164 // show select when clicking in a focused field
165 if ( hasFocus++ > 1 && !select.visible() ) {
168 }).bind("search", function() {
169 // TODO why not just specifying both arguments?
170 var fn = (arguments.length > 1) ? arguments[1] : null;
171 function findValueCallback(q, data) {
173 if( data && data.length ) {
174 for (var i=0; i < data.length; i++) {
175 if( data[i].result.toLowerCase() == q.toLowerCase() ) {
181 if( typeof fn == "function" ) fn(result);
182 else $input.trigger("result", result && [result.data, result.value]);
184 $.each(trimWords($input.val()), function(i, value) {
185 request(value, findValueCallback, findValueCallback);
187 }).bind("flushCache", function() {
189 }).bind("setOptions", function() {
190 $.extend(options, arguments[1]);
191 // if we've updated the data, repopulate
192 if ( "data" in arguments[1] )
194 }).bind("unautocomplete", function() {
197 $(input.form).unbind(".autocomplete");
201 function selectCurrent() {
202 var selected = select.selected();
206 var v = selected.result;
209 if ( options.multiple ) {
210 var words = trimWords($input.val());
211 if ( words.length > 1 ) {
212 v = words.slice(0, words.length - 1).join( options.multipleSeparator ) + options.multipleSeparator + v;
214 v += options.multipleSeparator;
219 $input.trigger("result", [selected.data, selected.value]);
223 function onChange(crap, skipPrevCheck) {
224 if( lastKeyPressCode == KEY.DEL ) {
229 var currentValue = $input.val();
231 if ( !skipPrevCheck && currentValue == previousValue )
234 previousValue = currentValue;
236 currentValue = lastWord(currentValue);
237 if ( currentValue.length >= options.minChars) {
238 $input.addClass(options.loadingClass);
239 if (!options.matchCase)
240 currentValue = currentValue.toLowerCase();
241 request(currentValue, receiveData, hideResultsNow);
248 function trimWords(value) {
252 var words = value.split( options.multipleSeparator );
254 $.each(words, function(i, value) {
256 result[i] = $.trim(value);
261 function lastWord(value) {
262 if ( !options.multiple )
264 var words = trimWords(value);
265 return words[words.length - 1];
268 // fills in the input box w/the first match (assumed to be the best match)
269 // q: the term entered
270 // sValue: the first matching result
271 function autoFill(q, sValue){
272 // autofill in the complete box w/the first match as long as the user hasn't entered in more data
273 // if the last user key pressed was backspace, don't autofill
274 if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {
275 // fill in the value (keep the case the user has typed)
276 $input.val($input.val() + sValue.substring(lastWord(previousValue).length));
277 // select the portion of the value not typed by the user (so the next character will erase)
278 $.Autocompleter.Selection(input, previousValue.length, previousValue.length + sValue.length);
282 function hideResults() {
283 clearTimeout(timeout);
284 timeout = setTimeout(hideResultsNow, 200);
287 function hideResultsNow() {
288 var wasVisible = select.visible();
290 clearTimeout(timeout);
292 if (options.mustMatch) {
293 // call search and run callback
296 // if no value found, clear the input box
298 if (options.multiple) {
299 var words = trimWords($input.val()).slice(0, -1);
300 $input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
309 // position cursor at end of input field
310 $.Autocompleter.Selection(input, input.value.length, input.value.length);
313 function receiveData(q, data) {
314 if ( data && data.length && hasFocus ) {
316 select.display(data, q);
317 autoFill(q, data[0].value);
324 function request(term, success, failure) {
325 if (!options.matchCase)
326 term = term.toLowerCase();
327 var data = cache.load(term);
328 // recieve the cached data
329 if (data && data.length) {
331 // if an AJAX url has been supplied, try loading the data now
332 } else if( (typeof options.url == "string") && (options.url.length > 0) ){
335 timestamp: +new Date()
337 $.each(options.extraParams, function(key, param) {
338 extraParams[key] = typeof param == "function" ? param() : param;
342 // try to leverage ajaxQueue plugin to abort previous requests
344 // limit abortion to this input
345 port: "autocomplete" + input.name,
346 dataType: options.dataType,
352 success: function(data) {
353 var parsed = options.parse && options.parse(data) || parse(data);
354 cache.add(term, parsed);
355 success(term, parsed);
359 // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
365 function parse(data) {
367 var rows = data.split("\n");
368 for (var i=0; i < rows.length; i++) {
369 var row = $.trim(rows[i]);
371 row = row.split("|");
372 parsed[parsed.length] = {
375 result: options.formatResult && options.formatResult(row, row[0]) || row[0]
382 function stopLoading() {
383 $input.removeClass(options.loadingClass);
388 $.Autocompleter.defaults = {
389 inputClass: "ac_input",
390 resultsClass: "ac_results",
391 loadingClass: "ac_loading",
396 matchContains: false,
402 formatItem: function(row) { return row[0]; },
407 multipleSeparator: ", ",
408 highlight: function(value, term) {
409 return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
415 $.Autocompleter.Cache = function(options) {
420 function matchSubset(s, sub) {
421 if (!options.matchCase)
423 var i = s.indexOf(sub);
424 if (i == -1) return false;
425 return i == 0 || options.matchContains;
428 function add(q, value) {
429 if (length > options.cacheLength){
439 if( !options.data ) return false;
441 var stMatchSets = {},
444 // no url was specified, we need to adjust the cache length to make sure it fits the local data store
445 if( !options.url ) options.cacheLength = 1;
447 // track all options for minChars = 0
448 stMatchSets[""] = [];
450 // loop through the array and create a lookup structure
451 for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
452 var rawValue = options.data[i];
453 // if rawValue is a string, make an array otherwise just reference the array
454 rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;
456 var value = options.formatMatch(rawValue, i+1, options.data.length);
457 if ( value === false )
460 var firstChar = value.charAt(0).toLowerCase();
461 // if no lookup array for this character exists, look it up now
462 if( !stMatchSets[firstChar] )
463 stMatchSets[firstChar] = [];
465 // if the match is a string
469 result: options.formatResult && options.formatResult(rawValue) || value
472 // push the current match into the set list
473 stMatchSets[firstChar].push(row);
475 // keep track of minChars zero items
476 if ( nullData++ < options.max ) {
477 stMatchSets[""].push(row);
481 // add the data items to the cache
482 $.each(stMatchSets, function(i, value) {
483 // increase the cache size
484 options.cacheLength++;
490 // populate any existing data
491 setTimeout(populate, 25);
503 if (!options.cacheLength || !length)
506 * if dealing w/local data and matchContains than we must make sure
507 * to loop through all the data collections looking for matches
509 if( !options.url && options.matchContains ){
512 // loop through all the data grids for matches
513 for( var k in data ){
514 // don't search through the stMatchSets[""] (minChars: 0) cache
515 // this prevents duplicates
518 $.each(c, function(i, x) {
519 // if we've got a match, add it to the array
520 if (matchSubset(x.value, q)) {
528 // if the exact item exists, use it
532 if (options.matchSubset) {
533 for (var i = q.length - 1; i >= options.minChars; i--) {
534 var c = data[q.substr(0, i)];
537 $.each(c, function(i, x) {
538 if (matchSubset(x.value, q)) {
539 csub[csub.length] = x;
551 $.Autocompleter.Select = function (options, input, select, config) {
568 element = $("<div/>")
570 .addClass(options.resultsClass)
571 .css("position", "absolute")
572 .appendTo(document.body);
574 list = $("<ul/>").appendTo(element).mouseover( function(event) {
575 if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
576 active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
577 $(target(event)).addClass(CLASSES.ACTIVE);
579 }).click(function(event) {
580 $(target(event)).addClass(CLASSES.ACTIVE);
582 // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
585 }).mousedown(function() {
586 config.mouseDownOnSelect = true;
587 }).mouseup(function() {
588 config.mouseDownOnSelect = false;
591 if( options.width > 0 )
592 element.css("width", options.width);
597 function target(event) {
598 var element = event.target;
599 while(element && element.tagName != "LI")
600 element = element.parentNode;
601 // more fun with IE, sometimes event.target is empty, just ignore it then
607 function moveSelect(step) {
608 listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
610 var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
613 listItems.slice(0, active).each(function() {
614 offset += this.offsetHeight;
616 if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
617 list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
618 } else if(offset < list.scrollTop()) {
619 list.scrollTop(offset);
624 function movePosition(step) {
627 active = listItems.size() - 1;
628 } else if (active >= listItems.size()) {
633 function limitNumberOfItems(available) {
634 return options.max && options.max < available
639 function fillList() {
641 var max = limitNumberOfItems(data.length);
642 for (var i=0; i < max; i++) {
645 var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
646 if ( formatted === false )
648 var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
649 $.data(li, "ac_data", data[i]);
651 listItems = list.find("li");
652 if ( options.selectFirst ) {
653 listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
656 // apply bgiframe if available
662 display: function(d, q) {
675 if (active != 0 && active - 8 < 0) {
676 moveSelect( -active );
681 pageDown: function() {
682 if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
683 moveSelect( listItems.size() - 1 - active );
689 element && element.hide();
690 listItems && listItems.removeClass(CLASSES.ACTIVE);
693 visible : function() {
694 return element && element.is(":visible");
696 current: function() {
697 return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
700 var offset = $(input).offset();
702 width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
703 top: offset.top + input.offsetHeight,
709 maxHeight: options.scrollHeight,
713 if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
715 listItems.each(function() {
716 listHeight += this.offsetHeight;
718 var scrollbarsVisible = listHeight > options.scrollHeight;
719 list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
720 if (!scrollbarsVisible) {
721 // IE doesn't recalculate width when scrollbar disappears
722 listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
728 selected: function() {
729 var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
730 return selected && selected.length && $.data(selected[0], "ac_data");
732 emptyList: function (){
733 list && list.empty();
736 element && element.remove();
741 $.Autocompleter.Selection = function(field, start, end) {
742 if( field.createTextRange ){
743 var selRange = field.createTextRange();
744 selRange.collapse(true);
745 selRange.moveStart("character", start);
746 selRange.moveEnd("character", end);
748 } else if( field.setSelectionRange ){
749 field.setSelectionRange(start, end);
751 if( field.selectionStart ){
752 field.selectionStart = start;
753 field.selectionEnd = end;