2
* Autocomplete - jQuery plugin 1.0
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 5329 2008-04-27 13:07:34Z 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);
81
$input.keydown(function(event) {
82
// track last key pressed
83
lastKeyPressCode = event.keyCode;
84
switch(event.keyCode) {
87
event.preventDefault();
88
if ( select.visible() ) {
96
event.preventDefault();
97
if ( select.visible() ) {
105
event.preventDefault();
106
if ( select.visible() ) {
114
event.preventDefault();
115
if ( select.visible() ) {
122
// matches also semicolon
123
case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
126
if( selectCurrent() ){
127
// make sure to blur off the current field
128
if( !options.multiple )
130
event.preventDefault();
139
clearTimeout(timeout);
140
timeout = setTimeout(onChange, options.delay);
143
}).keypress(function() {
144
// having fun with opera - remove this binding and Opera submits the form when we select an entry via return
146
// track whether the field has focus, we shouldn't process any
147
// results if the field no longer has focus
151
if (!config.mouseDownOnSelect) {
154
}).click(function() {
155
// show select when clicking in a focused field
156
if ( hasFocus++ > 1 && !select.visible() ) {
159
}).bind("search", function() {
160
// TODO why not just specifying both arguments?
161
var fn = (arguments.length > 1) ? arguments[1] : null;
162
function findValueCallback(q, data) {
164
if( data && data.length ) {
165
for (var i=0; i < data.length; i++) {
166
if( data[i].result.toLowerCase() == q.toLowerCase() ) {
172
if( typeof fn == "function" ) fn(result);
173
else $input.trigger("result", result && [result.data, result.value]);
175
$.each(trimWords($input.val()), function(i, value) {
176
request(value, findValueCallback, findValueCallback);
178
}).bind("flushCache", function() {
180
}).bind("setOptions", function() {
181
$.extend(options, arguments[1]);
182
// if we've updated the data, repopulate
183
if ( "data" in arguments[1] )
185
}).bind("unautocomplete", function() {
191
function selectCurrent() {
192
var selected = select.selected();
196
var v = selected.result;
199
if ( options.multiple ) {
200
var words = trimWords($input.val());
201
if ( words.length > 1 ) {
202
v = words.slice(0, words.length - 1).join( options.multipleSeparator ) + options.multipleSeparator + v;
204
v += options.multipleSeparator;
209
$input.trigger("result", [selected.data, selected.value]);
213
function onChange(crap, skipPrevCheck) {
214
if( lastKeyPressCode == KEY.DEL ) {
219
var currentValue = $input.val();
221
if ( !skipPrevCheck && currentValue == previousValue )
224
previousValue = currentValue;
226
currentValue = lastWord(currentValue);
227
if ( currentValue.length >= options.minChars) {
228
$input.addClass(options.loadingClass);
229
if (!options.matchCase)
230
currentValue = currentValue.toLowerCase();
231
request(currentValue, receiveData, hideResultsNow);
238
function trimWords(value) {
242
var words = value.split( options.multipleSeparator );
244
$.each(words, function(i, value) {
246
result[i] = $.trim(value);
251
function lastWord(value) {
252
if ( !options.multiple )
254
var words = trimWords(value);
255
return words[words.length - 1];
258
// fills in the input box w/the first match (assumed to be the best match)
259
// q: the term entered
260
// sValue: the first matching result
261
function autoFill(q, sValue){
262
// autofill in the complete box w/the first match as long as the user hasn't entered in more data
263
// if the last user key pressed was backspace, don't autofill
264
if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {
265
// fill in the value (keep the case the user has typed)
266
$input.val($input.val() + sValue.substring(lastWord(previousValue).length));
267
// select the portion of the value not typed by the user (so the next character will erase)
268
$.Autocompleter.Selection(input, previousValue.length, previousValue.length + sValue.length);
272
function hideResults() {
273
clearTimeout(timeout);
274
timeout = setTimeout(hideResultsNow, 200);
277
function hideResultsNow() {
279
clearTimeout(timeout);
281
if (options.mustMatch) {
282
// call search and run callback
285
// if no value found, clear the input box
286
if( !result ) $input.val("");
292
function receiveData(q, data) {
293
if ( data && data.length && hasFocus ) {
295
select.display(data, q);
296
autoFill(q, data[0].value);
303
function request(term, success, failure) {
304
if (!options.matchCase)
305
term = term.toLowerCase();
306
var data = cache.load(term);
307
// recieve the cached data
308
if (data && data.length) {
310
// if an AJAX url has been supplied, try loading the data now
311
} else if( (typeof options.url == "string") && (options.url.length > 0) ){
314
timestamp: +new Date()
316
$.each(options.extraParams, function(key, param) {
317
extraParams[key] = typeof param == "function" ? param() : param;
321
// try to leverage ajaxQueue plugin to abort previous requests
323
// limit abortion to this input
324
port: "autocomplete" + input.name,
325
dataType: options.dataType,
331
success: function(data) {
332
var parsed = options.parse && options.parse(data) || parse(data);
333
cache.add(term, parsed);
334
success(term, parsed);
338
// if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
344
function parse(data) {
346
var rows = data.split("\n");
347
for (var i=0; i < rows.length; i++) {
348
var row = $.trim(rows[i]);
350
row = row.split("|");
351
parsed[parsed.length] = {
354
result: options.formatResult && options.formatResult(row, row[0]) || row[0]
361
function stopLoading() {
362
$input.removeClass(options.loadingClass);
367
$.Autocompleter.defaults = {
368
inputClass: "ac_input",
369
resultsClass: "ac_results",
370
loadingClass: "ac_loading",
375
matchContains: false,
381
formatItem: function(row) { return row[0]; },
386
multipleSeparator: ", ",
387
highlight: function(value, term) {
388
return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
394
$.Autocompleter.Cache = function(options) {
399
function matchSubset(s, sub) {
400
if (!options.matchCase)
402
var i = s.indexOf(sub);
403
if (i == -1) return false;
404
return i == 0 || options.matchContains;
407
function add(q, value) {
408
if (length > options.cacheLength){
418
if( !options.data ) return false;
420
var stMatchSets = {},
423
// no url was specified, we need to adjust the cache length to make sure it fits the local data store
424
if( !options.url ) options.cacheLength = 1;
426
// track all options for minChars = 0
427
stMatchSets[""] = [];
429
// loop through the array and create a lookup structure
430
for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
431
var rawValue = options.data[i];
432
// if rawValue is a string, make an array otherwise just reference the array
433
rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;
435
var value = options.formatMatch(rawValue, i+1, options.data.length);
436
if ( value === false )
439
var firstChar = value.charAt(0).toLowerCase();
440
// if no lookup array for this character exists, look it up now
441
if( !stMatchSets[firstChar] )
442
stMatchSets[firstChar] = [];
444
// if the match is a string
448
result: options.formatResult && options.formatResult(rawValue) || value
451
// push the current match into the set list
452
stMatchSets[firstChar].push(row);
454
// keep track of minChars zero items
455
if ( nullData++ < options.max ) {
456
stMatchSets[""].push(row);
460
// add the data items to the cache
461
$.each(stMatchSets, function(i, value) {
462
// increase the cache size
463
options.cacheLength++;
469
// populate any existing data
470
setTimeout(populate, 25);
482
if (!options.cacheLength || !length)
485
* if dealing w/local data and matchContains than we must make sure
486
* to loop through all the data collections looking for matches
488
if( !options.url && options.matchContains ){
491
// loop through all the data grids for matches
492
for( var k in data ){
493
// don't search through the stMatchSets[""] (minChars: 0) cache
494
// this prevents duplicates
497
$.each(c, function(i, x) {
498
// if we've got a match, add it to the array
499
if (matchSubset(x.value, q)) {
507
// if the exact item exists, use it
511
if (options.matchSubset) {
512
for (var i = q.length - 1; i >= options.minChars; i--) {
513
var c = data[q.substr(0, i)];
516
$.each(c, function(i, x) {
517
if (matchSubset(x.value, q)) {
518
csub[csub.length] = x;
530
$.Autocompleter.Select = function (options, input, select, config) {
547
element = $($.create("div",{ns:xhtmlns},[]))
549
.addClass(options.resultsClass)
550
.css("position", "absolute")
551
.appendTo(document.body);
553
list = $($.create("ul",{ns:xhtmlns},[])).appendTo(element).mouseover( function(event) {
554
if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
555
active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
556
$(target(event)).addClass(CLASSES.ACTIVE);
558
}).click(function(event) {
559
$(target(event)).addClass(CLASSES.ACTIVE);
563
}).mousedown(function() {
564
config.mouseDownOnSelect = true;
565
}).mouseup(function() {
566
config.mouseDownOnSelect = false;
569
if( options.width > 0 )
570
element.css("width", options.width);
575
function target(event) {
576
var element = event.target;
577
while(element && element.tagName != "LI")
578
element = element.parentNode;
579
// more fun with IE, sometimes event.target is empty, just ignore it then
585
function moveSelect(step) {
586
listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
588
var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
591
listItems.slice(0, active).each(function() {
592
offset += this.offsetHeight;
594
if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
595
list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
596
} else if(offset < list.scrollTop()) {
597
list.scrollTop(offset);
602
function movePosition(step) {
605
active = listItems.size() - 1;
606
} else if (active >= listItems.size()) {
611
function limitNumberOfItems(available) {
612
return options.max && options.max < available
617
function fillList() {
619
var max = limitNumberOfItems(data.length);
620
for (var i=0; i < max; i++) {
623
var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
624
if ( formatted === false )
626
var li = $($.create("li",{ns:xhtmlns},[])).html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_event" : "ac_odd").appendTo(list)[0];
627
$.data(li, "ac_data", data[i]);
629
listItems = list.find("li");
630
if ( options.selectFirst ) {
631
listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
638
display: function(d, q) {
651
if (active != 0 && active - 8 < 0) {
652
moveSelect( -active );
657
pageDown: function() {
658
if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
659
moveSelect( listItems.size() - 1 - active );
665
element && element.hide();
668
visible : function() {
669
return element && element.is(":visible");
671
current: function() {
672
return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
675
var offset = $(input).offset();
677
width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
678
top: offset.top + input.offsetHeight,
684
maxHeight: options.scrollHeight,
688
if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
690
listItems.each(function() {
691
listHeight += this.offsetHeight;
693
var scrollbarsVisible = listHeight > options.scrollHeight;
694
list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
695
if (!scrollbarsVisible) {
696
// IE doesn't recalculate width when scrollbar disappears
697
listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
703
selected: function() {
704
var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
705
return selected && selected.length && $.data(selected[0], "ac_data");
707
emptyList: function (){
708
list && list.empty();
711
element && element.remove();
716
$.Autocompleter.Selection = function(field, start, end) {
717
if( field.createTextRange ){
718
var selRange = field.createTextRange();
719
selRange.collapse(true);
720
selRange.moveStart("character", start);
721
selRange.moveEnd("character", end);
723
} else if( field.setSelectionRange ){
724
field.setSelectionRange(start, end);
726
if( field.selectionStart ){
727
field.selectionStart = start;
728
field.selectionEnd = end;
b'\\ No newline at end of file'