jquery.autocomplete.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. /**
  2. * Ajax Autocomplete for jQuery, version 1.1.3
  3. * (c) 2010 Tomas Kirda
  4. *
  5. * Ajax Autocomplete for jQuery is freely distributable under the terms of an MIT-style license.
  6. * For details, see the web site: http://www.devbridge.com/projects/autocomplete/jquery/
  7. *
  8. * Last Review: 04/19/2010
  9. */
  10. /*jslint onevar: true, evil: true, nomen: true, eqeqeq: true, bitwise: true, regexp: true, newcap: true, immed: true */
  11. /*global window: true, document: true, clearInterval: true, setInterval: true, jQuery: true */
  12. (function($) {
  13. var reEscape = new RegExp('(\\' + ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'].join('|\\') + ')', 'g');
  14. function fnFormatResult(value, data, currentValue) {
  15. var pattern = '(' + currentValue.replace(reEscape, '\\$1') + ')';
  16. return value.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>');
  17. }
  18. function Autocomplete(el, options) {
  19. this.el = $(el);
  20. this.el.attr('autocomplete', 'off');
  21. this.suggestions = [];
  22. this.data = [];
  23. this.badQueries = [];
  24. this.selectedIndex = -1;
  25. this.currentValue = this.el.val();
  26. this.intervalId = 0;
  27. this.cachedResponse = [];
  28. this.onChangeInterval = null;
  29. this.ignoreValueChange = false;
  30. this.serviceUrl = options.serviceUrl;
  31. this.isLocal = false;
  32. this.options = {
  33. autoSubmit: false,
  34. minChars: 1,
  35. maxHeight: 300,
  36. deferRequestBy: 0,
  37. width: 0,
  38. highlight: true,
  39. params: {},
  40. fnFormatResult: fnFormatResult,
  41. delimiter: null,
  42. zIndex: 9999
  43. };
  44. this.initialize();
  45. this.setOptions(options);
  46. }
  47. $.fn.autocomplete = function(options) {
  48. return new Autocomplete(this.get(0)||$('<input />'), options);
  49. };
  50. Autocomplete.prototype = {
  51. killerFn: null,
  52. initialize: function() {
  53. var me, uid, autocompleteElId;
  54. me = this;
  55. uid = Math.floor(Math.random()*0x100000).toString(16);
  56. autocompleteElId = 'Autocomplete_' + uid;
  57. this.killerFn = function(e) {
  58. if ($(e.target).parents('.autocomplete').size() === 0) {
  59. me.killSuggestions();
  60. me.disableKillerFn();
  61. }
  62. };
  63. if (!this.options.width) { this.options.width = this.el.width(); }
  64. this.mainContainerId = 'AutocompleteContainter_' + uid;
  65. $('<div id="' + this.mainContainerId + '" style="position:absolute;z-index:9999;"><div class="autocomplete-w1"><div class="autocomplete" id="' + autocompleteElId + '" style="display:none; width:300px;"></div></div></div>').appendTo('body');
  66. this.container = $('#' + autocompleteElId);
  67. this.fixPosition();
  68. if (window.opera) {
  69. this.el.keypress(function(e) { me.onKeyPress(e); });
  70. } else {
  71. this.el.keydown(function(e) { me.onKeyPress(e); });
  72. }
  73. this.el.keyup(function(e) { me.onKeyUp(e); });
  74. this.el.blur(function() { me.enableKillerFn(); });
  75. this.el.focus(function() { me.fixPosition(); });
  76. },
  77. setOptions: function(options){
  78. var o = this.options;
  79. $.extend(o, options);
  80. if(o.lookup){
  81. this.isLocal = true;
  82. if($.isArray(o.lookup)){ o.lookup = { suggestions:o.lookup, data:[] }; }
  83. }
  84. $('#'+this.mainContainerId).css({ zIndex:o.zIndex+9999 });
  85. this.container.css({ maxHeight: o.maxHeight + 'px', width:o.width});
  86. },
  87. clearCache: function(){
  88. this.cachedResponse = [];
  89. this.badQueries = [];
  90. },
  91. disable: function(){
  92. this.disabled = true;
  93. },
  94. enable: function(){
  95. this.disabled = false;
  96. },
  97. fixPosition: function() {
  98. var offset = this.el.offset();
  99. $('#' + this.mainContainerId).css({ top: (offset.top + this.el.innerHeight())-2 + 'px', left: offset.left + 'px' });
  100. },
  101. enableKillerFn: function() {
  102. var me = this;
  103. $(document).bind('click', me.killerFn);
  104. },
  105. disableKillerFn: function() {
  106. var me = this;
  107. $(document).unbind('click', me.killerFn);
  108. },
  109. killSuggestions: function() {
  110. var me = this;
  111. this.stopKillSuggestions();
  112. this.intervalId = window.setInterval(function() { me.hide(); me.stopKillSuggestions(); }, 300);
  113. },
  114. stopKillSuggestions: function() {
  115. window.clearInterval(this.intervalId);
  116. },
  117. onKeyPress: function(e) {
  118. if (this.disabled || !this.enabled) { return; }
  119. // return will exit the function
  120. // and event will not be prevented
  121. switch (e.keyCode) {
  122. case 27: //KEY_ESC:
  123. this.el.val(this.currentValue);
  124. this.hide();
  125. break;
  126. case 9: //KEY_TAB:
  127. case 13: //KEY_RETURN:
  128. if (this.selectedIndex === -1) {
  129. this.hide();
  130. return;
  131. }
  132. this.select(this.selectedIndex);
  133. if(e.keyCode === 9){ return; }
  134. break;
  135. case 38: //KEY_UP:
  136. this.moveUp();
  137. break;
  138. case 40: //KEY_DOWN:
  139. this.moveDown();
  140. break;
  141. default:
  142. return;
  143. }
  144. e.stopImmediatePropagation();
  145. e.preventDefault();
  146. },
  147. onKeyUp: function(e) {
  148. if(this.disabled){ return; }
  149. switch (e.keyCode) {
  150. case 38: //KEY_UP:
  151. case 40: //KEY_DOWN:
  152. return;
  153. }
  154. clearInterval(this.onChangeInterval);
  155. if (this.currentValue !== this.el.val()) {
  156. if (this.options.deferRequestBy > 0) {
  157. // Defer lookup in case when value changes very quickly:
  158. var me = this;
  159. this.onChangeInterval = setInterval(function() { me.onValueChange(); }, this.options.deferRequestBy);
  160. } else {
  161. this.onValueChange();
  162. }
  163. }
  164. },
  165. onValueChange: function() {
  166. clearInterval(this.onChangeInterval);
  167. this.currentValue = this.el.val();
  168. var q = this.getQuery(this.currentValue);
  169. this.selectedIndex = -1;
  170. if (this.ignoreValueChange) {
  171. this.ignoreValueChange = false;
  172. return;
  173. }
  174. if (q === '' || q.length < this.options.minChars) {
  175. this.hide();
  176. } else {
  177. this.getSuggestions(q);
  178. }
  179. },
  180. getQuery: function(val) {
  181. var d, arr;
  182. d = this.options.delimiter;
  183. if (!d) { return $.trim(val); }
  184. arr = val.split(d);
  185. return $.trim(arr[arr.length - 1]);
  186. },
  187. getSuggestionsLocal: function(q) {
  188. var ret, arr, len, val, i;
  189. arr = this.options.lookup;
  190. len = arr.suggestions.length;
  191. ret = { suggestions:[], data:[] };
  192. q = q.toLowerCase();
  193. for(i=0; i< len; i++){
  194. val = arr.suggestions[i];
  195. if(val.toLowerCase().indexOf(q) === 0){
  196. ret.suggestions.push(val);
  197. ret.data.push(arr.data[i]);
  198. }
  199. }
  200. return ret;
  201. },
  202. getSuggestions: function(q) {
  203. var cr, me;
  204. cr = this.isLocal ? this.getSuggestionsLocal(q) : this.cachedResponse[q];
  205. if (cr && $.isArray(cr.suggestions)) {
  206. this.suggestions = cr.suggestions;
  207. this.data = cr.data;
  208. this.suggest();
  209. } else if (!this.isBadQuery(q)) {
  210. me = this;
  211. me.options.params.query = q;
  212. $.get(this.serviceUrl, me.options.params, function(txt) { me.processResponse(txt); }, 'text');
  213. }
  214. },
  215. isBadQuery: function(q) {
  216. var i = this.badQueries.length;
  217. while (i--) {
  218. if (q.indexOf(this.badQueries[i]) === 0) { return true; }
  219. }
  220. return false;
  221. },
  222. hide: function() {
  223. this.enabled = false;
  224. this.selectedIndex = -1;
  225. this.container.hide();
  226. },
  227. suggest: function() {
  228. if (this.suggestions.list.length === 0) {
  229. this.hide();
  230. return;
  231. }
  232. var me, len, div, f, v, i, s, mOver, mClick;
  233. me = this;
  234. len = this.suggestions.list.length;
  235. f = this.options.fnFormatResult;
  236. v = this.getQuery(this.currentValue);
  237. mOver = function(xi) { return function() { me.activate(xi); }; };
  238. mClick = function(xi) { return function() { me.select(xi); }; };
  239. this.container.hide().empty();
  240. for (i = 0; i < len; i++) {
  241. s = this.suggestions.list[i];
  242. div = $((me.selectedIndex === i ? '<div class="selected"' : '<div') + ' title="' + s.w_word + '">' + f(s.w_word, this.data[i], v) + '</div>');
  243. div.mouseover(mOver(i));
  244. div.click(mClick(i));
  245. this.container.append(div);
  246. }
  247. this.enabled = true;
  248. this.container.show();
  249. },
  250. processResponse: function(text) {
  251. var response;
  252. try {
  253. response = eval('(' + text + ')');
  254. } catch (err) { return; }
  255. if (!response.data) { return false; }
  256. if(!this.options.noCache){
  257. this.cachedResponse[response.data.query] = response;
  258. if (response.data.suggestions.length === 0) { this.badQueries.push(response.data.query); }
  259. }
  260. if (response.data.query === this.getQuery(this.currentValue)) {
  261. this.suggestions = response.data.suggestions;
  262. this.data = response.data;
  263. this.suggest();
  264. }
  265. },
  266. activate: function(index) {
  267. var divs, activeItem;
  268. divs = this.container.children();
  269. // Clear previous selection:
  270. if (this.selectedIndex !== -1 && divs.length > this.selectedIndex) {
  271. $(divs.get(this.selectedIndex)).removeClass();
  272. }
  273. this.selectedIndex = index;
  274. if (this.selectedIndex !== -1 && divs.length > this.selectedIndex) {
  275. activeItem = divs.get(this.selectedIndex);
  276. $(activeItem).addClass('selected');
  277. }
  278. return activeItem;
  279. },
  280. deactivate: function(div, index) {
  281. div.className = '';
  282. if (this.selectedIndex === index) { this.selectedIndex = -1; }
  283. },
  284. select: function(i) {
  285. var selectedValue, f;
  286. selectedValue = this.suggestions.list[i].w_word;
  287. if (selectedValue) {
  288. this.el.val(selectedValue);
  289. if (this.options.autoSubmit) {
  290. f = this.el.parents('form');
  291. if (f.length > 0) { f.get(0).submit(); }
  292. }
  293. this.ignoreValueChange = true;
  294. this.hide();
  295. this.onSelect(i);
  296. }
  297. },
  298. moveUp: function() {
  299. if (this.selectedIndex === -1) { return; }
  300. if (this.selectedIndex === 0) {
  301. this.container.children().get(0).className = '';
  302. this.selectedIndex = -1;
  303. this.el.val(this.currentValue);
  304. return;
  305. }
  306. this.adjustScroll(this.selectedIndex - 1);
  307. },
  308. moveDown: function() {
  309. if (this.selectedIndex === (this.suggestions.list.length - 1)) { return; }
  310. this.adjustScroll(this.selectedIndex + 1);
  311. },
  312. adjustScroll: function(i) {
  313. var activeItem, offsetTop, upperBound, lowerBound;
  314. activeItem = this.activate(i);
  315. offsetTop = activeItem.offsetTop;
  316. upperBound = this.container.scrollTop();
  317. lowerBound = upperBound + this.options.maxHeight - 25;
  318. if (offsetTop < upperBound) {
  319. this.container.scrollTop(offsetTop);
  320. } else if (offsetTop > lowerBound) {
  321. this.container.scrollTop(offsetTop - this.options.maxHeight + 25);
  322. }
  323. this.el.val(this.getValue(this.suggestions.list[i]));
  324. },
  325. onSelect: function(i) {
  326. var me, fn, s, d;
  327. me = this;
  328. fn = me.options.onSelect;
  329. s = me.suggestions[i];
  330. d = me.data[i];
  331. me.el.val(me.getValue(s));
  332. if ($.isFunction(fn)) { fn(s, d, me.el); }
  333. },
  334. getValue: function(value){
  335. value = value.w_word;
  336. var del, currVal, arr, me;
  337. me = this;
  338. del = me.options.delimiter;
  339. if (!del) { return value; }
  340. currVal = me.currentValue;
  341. arr = currVal.split(del);
  342. if (arr.length === 1) { return value; }
  343. return currVal.substr(0, currVal.length - arr[arr.length - 1].length) + value;
  344. }
  345. };
  346. }(jQuery));