jquery.autocomplete.js 11 KB

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