2
* jQuery Autocomplete plugin 1.1
4
* Modified for Yii Framework:
5
* - Renamed "autocomplete" to "legacyautocomplete".
6
* - Fixed IE8 problems (mario.ffranco).
8
* Copyright (c) 2009 Jörn Zaefferer
10
* Dual licensed under the MIT and GPL licenses:
11
* http://www.opensource.org/licenses/mit-license.php
12
* http://www.gnu.org/licenses/gpl.html
14
* Revision: $Id: jquery.autocomplete.js 15 2009-08-22 10:30:27Z joern.zaefferer $
20
legacyautocomplete: function(urlOrData, options) {
21
var isUrl = typeof urlOrData == "string";
22
options = $.extend({}, $.Autocompleter.defaults, {
23
url: isUrl ? urlOrData : null,
24
data: isUrl ? null : urlOrData,
25
delay: isUrl ? $.Autocompleter.defaults.delay : 10,
26
max: options && !options.scroll ? 10 : 150
29
// if highlight is set to false, replace it with a do-nothing function
30
options.highlight = options.highlight || function(value) { return value; };
32
// if the formatMatch option is not specified, then use formatItem for backwards compatibility
33
options.formatMatch = options.formatMatch || options.formatItem;
35
return this.each(function() {
36
new $.Autocompleter(this, options);
39
result: function(handler) {
40
return this.bind("result", handler);
42
search: function(handler) {
43
return this.trigger("search", [handler]);
45
flushCache: function() {
46
return this.trigger("flushCache");
48
setOptions: function(options){
49
return this.trigger("setOptions", [options]);
51
unautocomplete: function() {
52
return this.trigger("unautocomplete");
56
$.Autocompleter = function(input, options) {
71
// Create $ object for input element
72
var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);
75
var previousValue = "";
76
var cache = $.Autocompleter.Cache(options);
80
mouseDownOnSelect: false
82
var select = $.Autocompleter.Select(options, input, selectCurrent, config);
86
// prevent form submit in opera when selecting with return key
87
$.browser.opera && $(input.form).bind("submit.autocomplete", function() {
94
// only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
95
$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
96
// a keypress means the input has focus
97
// avoids issue where input had focus before the autocomplete was applied
99
// track last key pressed
100
lastKeyPressCode = event.keyCode;
101
switch(event.keyCode) {
104
event.preventDefault();
105
if ( select.visible() ) {
113
event.preventDefault();
114
if ( select.visible() ) {
122
event.preventDefault();
123
if ( select.visible() ) {
131
event.preventDefault();
132
if ( select.visible() ) {
139
// matches also semicolon
140
case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
143
if( selectCurrent() ) {
144
// stop default to prevent a form submit, Opera needs special handling
145
event.preventDefault();
156
clearTimeout(timeout);
157
timeout = setTimeout(onChange, options.delay);
161
// track whether the field has focus, we shouldn't process any
162
// results if the field no longer has focus
166
if (!config.mouseDownOnSelect) {
169
}).click(function() {
170
// show select when clicking in a focused field
171
if ( hasFocus++ > 1 && !select.visible() ) {
174
}).bind("search", function() {
175
// TODO why not just specifying both arguments?
176
var fn = (arguments.length > 1) ? arguments[1] : null;
177
function findValueCallback(q, data) {
179
if( data && data.length ) {
180
for (var i=0; i < data.length; i++) {
181
if( data[i].result.toLowerCase() == q.toLowerCase() ) {
187
if( typeof fn == "function" ) fn(result);
188
else $input.trigger("result", result && [result.data, result.value]);
190
$.each(trimWords($input.val()), function(i, value) {
191
request(value, findValueCallback, findValueCallback);
193
}).bind("flushCache", function() {
195
}).bind("setOptions", function() {
196
$.extend(options, arguments[1]);
197
// if we've updated the data, repopulate
198
if ( "data" in arguments[1] )
200
}).bind("unautocomplete", function() {
203
$(input.form).unbind(".autocomplete");
207
function selectCurrent() {
208
var selected = select.selected();
212
var v = selected.result;
215
if ( options.multiple ) {
216
var words = trimWords($input.val());
217
if ( words.length > 1 ) {
218
var seperator = options.multipleSeparator.length;
219
var cursorAt = $(input).selection().start;
220
var wordAt, progress = 0;
221
$.each(words, function(i, word) {
222
progress += word.length;
223
if (cursorAt <= progress) {
225
// Following return caused IE8 to set cursor to the start of the line.
228
progress += seperator;
231
// TODO this should set the cursor to the right position, but it gets overriden somewhere
232
//$.Autocompleter.Selection(input, progress + seperator, progress + seperator);
233
v = words.join( options.multipleSeparator );
235
v += options.multipleSeparator;
240
$input.trigger("result", [selected.data, selected.value]);
244
function onChange(crap, skipPrevCheck) {
245
if( lastKeyPressCode == KEY.DEL ) {
250
var currentValue = $input.val();
252
if ( !skipPrevCheck && currentValue == previousValue )
255
previousValue = currentValue;
257
currentValue = lastWord(currentValue);
258
if ( currentValue.length >= options.minChars) {
259
$input.addClass(options.loadingClass);
260
if (!options.matchCase)
261
currentValue = currentValue.toLowerCase();
262
request(currentValue, receiveData, hideResultsNow);
269
function trimWords(value) {
272
if (!options.multiple)
273
return [$.trim(value)];
274
return $.map(value.split(options.multipleSeparator), function(word) {
275
return $.trim(value).length ? $.trim(word) : null;
279
function lastWord(value) {
280
if ( !options.multiple )
282
var words = trimWords(value);
283
if (words.length == 1)
285
var cursorAt = $(input).selection().start;
286
if (cursorAt == value.length) {
287
words = trimWords(value)
289
words = trimWords(value.replace(value.substring(cursorAt), ""));
291
return words[words.length - 1];
294
// fills in the input box w/the first match (assumed to be the best match)
295
// q: the term entered
296
// sValue: the first matching result
297
function autoFill(q, sValue){
298
// autofill in the complete box w/the first match as long as the user hasn't entered in more data
299
// if the last user key pressed was backspace, don't autofill
300
if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {
301
// fill in the value (keep the case the user has typed)
302
$input.val($input.val() + sValue.substring(lastWord(previousValue).length));
303
// select the portion of the value not typed by the user (so the next character will erase)
304
$(input).selection(previousValue.length, previousValue.length + sValue.length);
308
function hideResults() {
309
clearTimeout(timeout);
310
timeout = setTimeout(hideResultsNow, 200);
313
function hideResultsNow() {
314
var wasVisible = select.visible();
316
clearTimeout(timeout);
318
if (options.mustMatch) {
319
// call search and run callback
322
// if no value found, clear the input box
324
if (options.multiple) {
325
var words = trimWords($input.val()).slice(0, -1);
326
$input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
330
$input.trigger("result", null);
338
function receiveData(q, data) {
339
if ( data && data.length && hasFocus ) {
341
select.display(data, q);
342
autoFill(q, data[0].value);
349
function request(term, success, failure) {
350
if (!options.matchCase)
351
term = term.toLowerCase();
352
var data = cache.load(term);
353
// recieve the cached data
354
if (data && data.length) {
356
// if an AJAX url has been supplied, try loading the data now
357
} else if( (typeof options.url == "string") && (options.url.length > 0) ){
360
timestamp: +new Date()
362
$.each(options.extraParams, function(key, param) {
363
extraParams[key] = typeof param == "function" ? param() : param;
367
// try to leverage ajaxQueue plugin to abort previous requests
369
// limit abortion to this input
370
port: "autocomplete" + input.name,
371
dataType: options.dataType,
377
success: function(data) {
378
var parsed = options.parse && options.parse(data) || parse(data);
379
cache.add(term, parsed);
380
success(term, parsed);
384
// if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
390
function parse(data) {
392
var rows = data.split("\n");
393
for (var i=0; i < rows.length; i++) {
394
var row = $.trim(rows[i]);
396
row = row.split("|");
397
parsed[parsed.length] = {
400
result: options.formatResult && options.formatResult(row, row[0]) || row[0]
407
function stopLoading() {
408
$input.removeClass(options.loadingClass);
413
$.Autocompleter.defaults = {
414
inputClass: "ac_input",
415
resultsClass: "ac_results",
416
loadingClass: "ac_loading",
421
matchContains: false,
427
formatItem: function(row) { return row[0]; },
432
multipleSeparator: ", ",
433
highlight: function(value, term) {
434
return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
440
$.Autocompleter.Cache = function(options) {
445
function matchSubset(s, sub) {
446
if (!options.matchCase)
448
var i = s.indexOf(sub);
449
if (options.matchContains == "word"){
450
i = s.toLowerCase().search("\\b" + sub.toLowerCase());
452
if (i == -1) return false;
453
return i == 0 || options.matchContains;
456
function add(q, value) {
457
if (length > options.cacheLength){
467
if( !options.data ) return false;
469
var stMatchSets = {},
472
// no url was specified, we need to adjust the cache length to make sure it fits the local data store
473
if( !options.url ) options.cacheLength = 1;
475
// track all options for minChars = 0
476
stMatchSets[""] = [];
478
// loop through the array and create a lookup structure
479
for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
480
var rawValue = options.data[i];
481
// if rawValue is a string, make an array otherwise just reference the array
482
rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;
484
var value = options.formatMatch(rawValue, i+1, options.data.length);
485
if ( value === false )
488
var firstChar = value.charAt(0).toLowerCase();
489
// if no lookup array for this character exists, look it up now
490
if( !stMatchSets[firstChar] )
491
stMatchSets[firstChar] = [];
493
// if the match is a string
497
result: options.formatResult && options.formatResult(rawValue) || value
500
// push the current match into the set list
501
stMatchSets[firstChar].push(row);
503
// keep track of minChars zero items
504
if ( nullData++ < options.max ) {
505
stMatchSets[""].push(row);
509
// add the data items to the cache
510
$.each(stMatchSets, function(i, value) {
511
// increase the cache size
512
options.cacheLength++;
518
// populate any existing data
519
setTimeout(populate, 25);
531
if (!options.cacheLength || !length)
534
* if dealing w/local data and matchContains than we must make sure
535
* to loop through all the data collections looking for matches
537
if( !options.url && options.matchContains ){
540
// loop through all the data grids for matches
541
for( var k in data ){
542
// don't search through the stMatchSets[""] (minChars: 0) cache
543
// this prevents duplicates
546
$.each(c, function(i, x) {
547
// if we've got a match, add it to the array
548
if (matchSubset(x.value, q)) {
556
// if the exact item exists, use it
560
if (options.matchSubset) {
561
for (var i = q.length - 1; i >= options.minChars; i--) {
562
var c = data[q.substr(0, i)];
565
$.each(c, function(i, x) {
566
if (matchSubset(x.value, q)) {
567
csub[csub.length] = x;
579
$.Autocompleter.Select = function (options, input, select, config) {
596
element = $("<div/>")
598
.addClass(options.resultsClass)
599
.css("position", "absolute")
600
.appendTo(document.body);
602
list = $("<ul/>").appendTo(element).mouseover( function(event) {
603
if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
604
active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
605
$(target(event)).addClass(CLASSES.ACTIVE);
607
}).click(function(event) {
608
$(target(event)).addClass(CLASSES.ACTIVE);
610
// TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
613
}).mousedown(function() {
614
config.mouseDownOnSelect = true;
615
}).mouseup(function() {
616
config.mouseDownOnSelect = false;
619
if( options.width > 0 )
620
element.css("width", options.width);
625
function target(event) {
626
var element = event.target;
627
while(element && element.tagName != "LI")
628
element = element.parentNode;
629
// more fun with IE, sometimes event.target is empty, just ignore it then
635
function moveSelect(step) {
636
listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
638
var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
641
listItems.slice(0, active).each(function() {
642
offset += this.offsetHeight;
644
if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
645
list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
646
} else if(offset < list.scrollTop()) {
647
list.scrollTop(offset);
652
function movePosition(step) {
655
active = listItems.size() - 1;
656
} else if (active >= listItems.size()) {
661
function limitNumberOfItems(available) {
662
return options.max && options.max < available
667
function fillList() {
669
var max = limitNumberOfItems(data.length);
670
for (var i=0; i < max; i++) {
673
var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
674
if ( formatted === false )
676
var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
677
$.data(li, "ac_data", data[i]);
679
listItems = list.find("li");
680
if ( options.selectFirst ) {
681
listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
684
// apply bgiframe if available
690
display: function(d, q) {
703
if (active != 0 && active - 8 < 0) {
704
moveSelect( -active );
709
pageDown: function() {
710
if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
711
moveSelect( listItems.size() - 1 - active );
717
element && element.hide();
718
listItems && listItems.removeClass(CLASSES.ACTIVE);
721
visible : function() {
722
return element && element.is(":visible");
724
current: function() {
725
return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
728
var offset = $(input).offset();
730
width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
731
top: offset.top + input.offsetHeight,
737
maxHeight: options.scrollHeight,
741
if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
743
listItems.each(function() {
744
listHeight += this.offsetHeight;
746
var scrollbarsVisible = listHeight > options.scrollHeight;
747
list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
748
if (!scrollbarsVisible) {
749
// IE doesn't recalculate width when scrollbar disappears
750
listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
756
selected: function() {
757
var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
758
return selected && selected.length && $.data(selected[0], "ac_data");
760
emptyList: function (){
761
list && list.empty();
764
element && element.remove();
769
$.fn.selection = function(start, end) {
770
if (start !== undefined) {
771
return this.each(function() {
772
if( this.createTextRange ){
773
var selRange = this.createTextRange();
774
if (end === undefined || start == end) {
775
selRange.move("character", start);
778
selRange.collapse(true);
779
selRange.moveStart("character", start);
780
selRange.moveEnd("character", end);
783
} else if( this.setSelectionRange ){
784
this.setSelectionRange(start, end);
785
} else if( this.selectionStart ){
786
this.selectionStart = start;
787
this.selectionEnd = end;
792
if ( field.createTextRange ) {
793
var range = document.selection.createRange(),
796
textLength = range.text.length;
797
range.text = teststring;
798
var caretAt = field.value.indexOf(teststring);
800
this.selection(caretAt, caretAt + textLength);
803
end: caretAt + textLength
805
} else if( field.selectionStart !== undefined ){
807
start: field.selectionStart,
808
end: field.selectionEnd
b'\\ No newline at end of file'