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) {
107 event.preventDefault();
108 if ( select.visible() ) {
116 event.preventDefault();
117 if ( select.visible() ) {
125 event.preventDefault();
126 if ( select.visible() ) {
134 event.preventDefault();
135 if ( select.visible() ) {
142 // matches also semicolon
143 case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
146 if( selectCurrent() ) {
147 // stop default to prevent a form submit, Opera needs special handling
148 event.preventDefault();
159 clearTimeout(timeout);
160 timeout = setTimeout(onChange, options.delay);
164 // track whether the field has focus, we shouldn't process any
165 // results if the field no longer has focus
169 if (!config.mouseDownOnSelect) {
172 }).click(function() {
173 // show select when clicking in a focused field
174 if ( hasFocus++ > 1 && !select.visible() ) {
177 }).bind("search", function() {
178 // TODO why not just specifying both arguments?
179 var fn = (arguments.length > 1) ? arguments[1] : null;
180 function findValueCallback(q, data) {
182 if( data && data.length ) {
183 for (var i=0; i < data.length; i++) {
184 if( data[i].result.toLowerCase() == q.toLowerCase() ) {
190 if( typeof fn == "function" ) fn(result);
191 else $input.trigger("result", result && [result.data, result.value]);
193 $.each(trimWords($input.val()), function(i, value) {
194 request(value, findValueCallback, findValueCallback);
196 }).bind("flushCache", function() {
198 }).bind("setOptions", function() {
199 $.extend(options, arguments[1]);
200 // if we've updated the data, repopulate
201 if ( "data" in arguments[1] )
203 }).bind("unautocomplete", function() {
206 $(input.form).unbind(".autocomplete");
210 function selectCurrent() {
211 var selected = select.selected();
215 var v = selected.result;
218 if ( options.multiple ) {
219 var words = trimWords($input.val());
220 if ( words.length > 1 ) {
221 var seperator = options.multipleSeparator.length;
222 var cursorAt = $(input).selection().start;
223 var wordAt, progress = 0;
224 $.each(words, function(i, word) {
225 progress += word.length;
226 if (cursorAt <= progress) {
230 progress += seperator;
233 // TODO this should set the cursor to the right position, but it gets overriden somewhere
234 //$.Autocompleter.Selection(input, progress + seperator, progress + seperator);
235 v = words.join( options.multipleSeparator );
237 v += options.multipleSeparator;
242 $input.trigger("result", [selected.data, selected.value]);
246 function onChange(crap, skipPrevCheck) {
247 if( lastKeyPressCode == KEY.DEL ) {
252 var currentValue = $input.val();
254 if ( !skipPrevCheck && currentValue == previousValue )
257 previousValue = currentValue;
259 currentValue = lastWord(currentValue);
260 if ( currentValue.length >= options.minChars) {
261 $input.addClass(options.loadingClass);
262 if (!options.matchCase)
263 currentValue = currentValue.toLowerCase();
264 request(currentValue, receiveData, hideResultsNow);
271 function trimWords(value) {
274 if (!options.multiple)
275 return [$.trim(value)];
276 return $.map(value.split(options.multipleSeparator), function(word) {
277 return $.trim(value).length ? $.trim(word) : null;
281 function lastWord(value) {
282 if ( !options.multiple )
284 var words = trimWords(value);
285 if (words.length == 1)
287 var cursorAt = $(input).selection().start;
288 if (cursorAt == value.length) {
289 words = trimWords(value)
291 words = trimWords(value.replace(value.substring(cursorAt), ""));
293 return words[words.length - 1];
296 // fills in the input box w/the first match (assumed to be the best match)
297 // q: the term entered
298 // sValue: the first matching result
299 function autoFill(q, sValue){
300 // autofill in the complete box w/the first match as long as the user hasn't entered in more data
301 // if the last user key pressed was backspace, don't autofill
302 if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {
303 // fill in the value (keep the case the user has typed)
304 $input.val($input.val() + sValue.substring(lastWord(previousValue).length));
305 // select the portion of the value not typed by the user (so the next character will erase)
306 $(input).selection(previousValue.length, previousValue.length + sValue.length);
310 function hideResults() {
311 clearTimeout(timeout);
312 timeout = setTimeout(hideResultsNow, 200);
315 function hideResultsNow() {
316 var wasVisible = select.visible();
318 clearTimeout(timeout);
320 if (options.mustMatch) {
321 // call search and run callback
324 // if no value found, clear the input box
326 if (options.multiple) {
327 var words = trimWords($input.val()).slice(0, -1);
328 $input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
332 $input.trigger("result", null);
340 function receiveData(q, data) {
341 if ( data && data.length && hasFocus ) {
343 select.display(data, q);
344 autoFill(q, data[0].value);
351 function request(term, success, failure) {
352 if (!options.matchCase)
353 term = term.toLowerCase();
354 var data = cache.load(term);
355 // recieve the cached data
356 if (data && data.length) {
358 // if an AJAX url has been supplied, try loading the data now
359 } else if( (typeof options.url == "string") && (options.url.length > 0) ){
362 timestamp: +new Date()
364 $.each(options.extraParams, function(key, param) {
365 extraParams[key] = typeof param == "function" ? param() : param;
369 // try to leverage ajaxQueue plugin to abort previous requests
371 // limit abortion to this input
372 port: "autocomplete" + input.name,
373 dataType: options.dataType,
379 success: function(data) {
380 var parsed = options.parse && options.parse(data) || parse(data);
381 cache.add(term, parsed);
382 success(term, parsed);
386 // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
392 function parse(data) {
394 var rows = data.split("\n");
395 for (var i=0; i < rows.length; i++) {
396 var row = $.trim(rows[i]);
398 row = row.split("|");
399 parsed[parsed.length] = {
402 result: options.formatResult && options.formatResult(row, row[0]) || row[0]
409 function stopLoading() {
410 $input.removeClass(options.loadingClass);
415 $.Autocompleter.defaults = {
416 inputClass: "ac_input",
417 resultsClass: "ac_results",
418 loadingClass: "ac_loading",
423 matchContains: false,
429 formatItem: function(row) { return row[0]; },
434 multipleSeparator: ", ",
435 highlight: function(value, term) {
436 return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
442 $.Autocompleter.Cache = function(options) {
447 function matchSubset(s, sub) {
448 if (!options.matchCase)
450 var i = s.indexOf(sub);
451 if (options.matchContains == "word"){
452 i = s.toLowerCase().search("\\b" + sub.toLowerCase());
454 if (i == -1) return false;
455 return i == 0 || options.matchContains;
458 function add(q, value) {
459 if (length > options.cacheLength){
469 if( !options.data ) return false;
471 var stMatchSets = {},
474 // no url was specified, we need to adjust the cache length to make sure it fits the local data store
475 if( !options.url ) options.cacheLength = 1;
477 // track all options for minChars = 0
478 stMatchSets[""] = [];
480 // loop through the array and create a lookup structure
481 for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
482 var rawValue = options.data[i];
483 // if rawValue is a string, make an array otherwise just reference the array
484 rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;
486 var value = options.formatMatch(rawValue, i+1, options.data.length);
487 if ( value === false )
490 var firstChar = value.charAt(0).toLowerCase();
491 // if no lookup array for this character exists, look it up now
492 if( !stMatchSets[firstChar] )
493 stMatchSets[firstChar] = [];
495 // if the match is a string
499 result: options.formatResult && options.formatResult(rawValue) || value
502 // push the current match into the set list
503 stMatchSets[firstChar].push(row);
505 // keep track of minChars zero items
506 if ( nullData++ < options.max ) {
507 stMatchSets[""].push(row);
511 // add the data items to the cache
512 $.each(stMatchSets, function(i, value) {
513 // increase the cache size
514 options.cacheLength++;
520 // populate any existing data
521 setTimeout(populate, 25);
533 if (!options.cacheLength || !length)
536 * if dealing w/local data and matchContains than we must make sure
537 * to loop through all the data collections looking for matches
539 if( !options.url && options.matchContains ){
542 // loop through all the data grids for matches
543 for( var k in data ){
544 // don't search through the stMatchSets[""] (minChars: 0) cache
545 // this prevents duplicates
548 $.each(c, function(i, x) {
549 // if we've got a match, add it to the array
550 if (matchSubset(x.value, q)) {
558 // if the exact item exists, use it
562 if (options.matchSubset) {
563 for (var i = q.length - 1; i >= options.minChars; i--) {
564 var c = data[q.substr(0, i)];
567 $.each(c, function(i, x) {
568 if (matchSubset(x.value, q)) {
569 csub[csub.length] = x;
581 $.Autocompleter.Select = function (options, input, select, config) {
598 element = $("<div/>")
600 .addClass(options.resultsClass)
601 .css("position", "absolute")
602 .appendTo(document.body);
604 list = $("<ul/>").appendTo(element).mouseover( function(event) {
605 if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
606 active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
607 $(target(event)).addClass(CLASSES.ACTIVE);
609 }).click(function(event) {
610 $(target(event)).addClass(CLASSES.ACTIVE);
612 // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
615 }).mousedown(function() {
616 config.mouseDownOnSelect = true;
617 }).mouseup(function() {
618 config.mouseDownOnSelect = false;
621 if( options.width > 0 )
622 element.css("width", options.width);
627 function target(event) {
628 var element = event.target;
629 while(element && element.tagName != "LI")
630 element = element.parentNode;
631 // more fun with IE, sometimes event.target is empty, just ignore it then
637 function moveSelect(step) {
638 listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
640 var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
643 listItems.slice(0, active).each(function() {
644 offset += this.offsetHeight;
646 if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
647 list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
648 } else if(offset < list.scrollTop()) {
649 list.scrollTop(offset);
654 function movePosition(step) {
657 active = listItems.size() - 1;
658 } else if (active >= listItems.size()) {
663 function limitNumberOfItems(available) {
664 return options.max && options.max < available
669 function fillList() {
671 var max = limitNumberOfItems(data.length);
672 for (var i=0; i < max; i++) {
675 var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
676 if ( formatted === false )
678 var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
679 $.data(li, "ac_data", data[i]);
681 listItems = list.find("li");
682 if ( options.selectFirst ) {
683 listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
686 // apply bgiframe if available
692 display: function(d, q) {
705 if (active != 0 && active - 8 < 0) {
706 moveSelect( -active );
711 pageDown: function() {
712 if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
713 moveSelect( listItems.size() - 1 - active );
719 element && element.hide();
720 listItems && listItems.removeClass(CLASSES.ACTIVE);
723 visible : function() {
724 return element && element.is(":visible");
726 current: function() {
727 return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
730 var offset = $(input).offset();
732 width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
733 top: offset.top + input.offsetHeight,
739 maxHeight: options.scrollHeight,
743 if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
745 listItems.each(function() {
746 listHeight += this.offsetHeight;
748 var scrollbarsVisible = listHeight > options.scrollHeight;
749 list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
750 if (!scrollbarsVisible) {
751 // IE doesn't recalculate width when scrollbar disappears
752 listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
758 selected: function() {
759 var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
760 return selected && selected.length && $.data(selected[0], "ac_data");
762 emptyList: function (){
763 list && list.empty();
766 element && element.remove();
771 $.fn.selection = function(start, end) {
772 if (start !== undefined) {
773 return this.each(function() {
774 if( this.createTextRange ){
775 var selRange = this.createTextRange();
776 if (end === undefined || start == end) {
777 selRange.move("character", start);
780 selRange.collapse(true);
781 selRange.moveStart("character", start);
782 selRange.moveEnd("character", end);
785 } else if( this.setSelectionRange ){
786 this.setSelectionRange(start, end);
787 } else if( this.selectionStart ){
788 this.selectionStart = start;
789 this.selectionEnd = end;
794 if ( field.createTextRange ) {
795 var range = document.selection.createRange(),
798 textLength = range.text.length;
799 range.text = teststring;
800 var caretAt = field.value.indexOf(teststring);
802 this.selection(caretAt, caretAt + textLength);
805 end: caretAt + textLength
807 } else if( field.selectionStart !== undefined ){
809 start: field.selectionStart,
810 end: field.selectionEnd