jquery.autocomplete.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. /**
  2. * Ajax Autocomplete for jQuery, version 1.2.7
  3. * (c) 2013 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. */
  9. /*jslint browser: true, white: true, plusplus: true */
  10. /*global define, window, document, jQuery */
  11. // Expose plugin as an AMD module if AMD loader is present:
  12. (function (factory) {
  13. 'use strict';
  14. if (typeof define === 'function' && define.amd) {
  15. // AMD. Register as an anonymous module.
  16. define(['jquery'], factory);
  17. } else {
  18. // Browser globals
  19. factory(jQuery);
  20. }
  21. }(function ($) {
  22. 'use strict';
  23. var
  24. utils = (function () {
  25. return {
  26. extend: function (target, source) {
  27. return $.extend(target, source);
  28. },
  29. createNode: function (html) {
  30. var div = document.createElement('div');
  31. div.innerHTML = html;
  32. return div.firstChild;
  33. }
  34. };
  35. }()),
  36. keys = {
  37. ESC: 27,
  38. TAB: 9,
  39. RETURN: 13,
  40. UP: 38,
  41. DOWN: 40
  42. };
  43. function Autocomplete(el, options) {
  44. var noop = function () { },
  45. that = this,
  46. defaults = {
  47. autoSelectFirst: false,
  48. appendTo: 'body',
  49. serviceUrl: null,
  50. lookup: null,
  51. onSelect: null,
  52. width: 'auto',
  53. minChars: 1,
  54. maxHeight: 300,
  55. deferRequestBy: 0,
  56. params: {},
  57. formatResult: Autocomplete.formatResult,
  58. delimiter: null,
  59. zIndex: 9999,
  60. type: 'GET',
  61. noCache: false,
  62. onSearchStart: noop,
  63. onSearchComplete: noop,
  64. containerClass: 'autocomplete-suggestions',
  65. tabDisabled: false,
  66. dataType: 'text',
  67. lookupFilter: function (suggestion, originalQuery, queryLowerCase) {
  68. return suggestion.value.toLowerCase().indexOf(queryLowerCase) !== -1;
  69. },
  70. paramName: 'query',
  71. transformResult: function (response) {
  72. return typeof response === 'string' ? $.parseJSON(response) : response;
  73. }
  74. };
  75. // Shared variables:
  76. that.element = el;
  77. that.el = $(el);
  78. that.suggestions = [];
  79. that.badQueries = [];
  80. that.selectedIndex = -1;
  81. that.currentValue = that.element.value;
  82. that.intervalId = 0;
  83. that.cachedResponse = [];
  84. that.onChangeInterval = null;
  85. that.onChange = null;
  86. that.ignoreValueChange = false;
  87. that.isLocal = false;
  88. that.suggestionsContainer = null;
  89. that.options = $.extend({}, defaults, options);
  90. that.classes = {
  91. selected: 'autocomplete-selected',
  92. suggestion: 'autocomplete-suggestion'
  93. };
  94. // Initialize and set options:
  95. that.initialize();
  96. that.setOptions(options);
  97. }
  98. Autocomplete.utils = utils;
  99. $.Autocomplete = Autocomplete;
  100. Autocomplete.formatResult = function (suggestion, currentValue) {
  101. var reEscape = new RegExp('(\\' + ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'].join('|\\') + ')', 'g'),
  102. pattern = '(' + currentValue.replace(reEscape, '\\$1') + ')';
  103. return suggestion.value.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>');
  104. };
  105. Autocomplete.prototype = {
  106. killerFn: null,
  107. initialize: function () {
  108. var that = this,
  109. suggestionSelector = '.' + that.classes.suggestion,
  110. selected = that.classes.selected,
  111. options = that.options,
  112. container;
  113. // Remove autocomplete attribute to prevent native suggestions:
  114. that.element.setAttribute('autocomplete', 'off');
  115. that.killerFn = function (e) {
  116. if ($(e.target).closest('.' + that.options.containerClass).length === 0) {
  117. that.killSuggestions();
  118. that.disableKillerFn();
  119. }
  120. };
  121. // Determine suggestions width:
  122. if (!options.width || options.width === 'auto') {
  123. options.width = that.el.outerWidth();
  124. }
  125. that.suggestionsContainer = Autocomplete.utils.createNode('<div class="' + options.containerClass + '" style="position: absolute; display: none;"></div>');
  126. container = $(that.suggestionsContainer);
  127. container.appendTo(options.appendTo).width(options.width);
  128. // Listen for mouse over event on suggestions list:
  129. container.on('mouseover.autocomplete', suggestionSelector, function () {
  130. that.activate($(this).data('index'));
  131. });
  132. // Deselect active element when mouse leaves suggestions container:
  133. container.on('mouseout.autocomplete', function () {
  134. that.selectedIndex = -1;
  135. container.children('.' + selected).removeClass(selected);
  136. });
  137. // Listen for click event on suggestions list:
  138. container.on('click.autocomplete', suggestionSelector, function () {
  139. that.select($(this).data('index'), false);
  140. });
  141. that.fixPosition();
  142. // Opera does not like keydown:
  143. if (window.opera) {
  144. that.el.on('keypress.autocomplete', function (e) { that.onKeyPress(e); });
  145. } else {
  146. that.el.on('keydown.autocomplete', function (e) { that.onKeyPress(e); });
  147. }
  148. that.el.on('keyup.autocomplete', function (e) { that.onKeyUp(e); });
  149. that.el.on('blur.autocomplete', function () { that.onBlur(); });
  150. that.el.on('focus.autocomplete', function () { that.fixPosition(); });
  151. },
  152. onBlur: function () {
  153. this.enableKillerFn();
  154. },
  155. setOptions: function (suppliedOptions) {
  156. var that = this,
  157. options = that.options;
  158. utils.extend(options, suppliedOptions);
  159. that.isLocal = $.isArray(options.lookup);
  160. if (that.isLocal) {
  161. options.lookup = that.verifySuggestionsFormat(options.lookup);
  162. }
  163. // Adjust height, width and z-index:
  164. $(that.suggestionsContainer).css({
  165. 'max-height': options.maxHeight + 'px',
  166. 'width': options.width + 'px',
  167. 'z-index': options.zIndex
  168. });
  169. },
  170. clearCache: function () {
  171. this.cachedResponse = [];
  172. this.badQueries = [];
  173. },
  174. clear: function () {
  175. this.clearCache();
  176. this.currentValue = null;
  177. this.suggestions = [];
  178. },
  179. disable: function () {
  180. this.disabled = true;
  181. },
  182. enable: function () {
  183. this.disabled = false;
  184. },
  185. fixPosition: function () {
  186. var that = this,
  187. offset;
  188. // Don't adjsut position if custom container has been specified:
  189. if (that.options.appendTo !== 'body') {
  190. return;
  191. }
  192. offset = that.el.offset();
  193. $(that.suggestionsContainer).css({
  194. top: (offset.top + that.el.outerHeight()) + 'px',
  195. left: offset.left + 'px'
  196. });
  197. },
  198. enableKillerFn: function () {
  199. var that = this;
  200. $(document).on('click.autocomplete', that.killerFn);
  201. },
  202. disableKillerFn: function () {
  203. var that = this;
  204. $(document).off('click.autocomplete', that.killerFn);
  205. },
  206. killSuggestions: function () {
  207. var that = this;
  208. that.stopKillSuggestions();
  209. that.intervalId = window.setInterval(function () {
  210. that.hide();
  211. that.stopKillSuggestions();
  212. }, 300);
  213. },
  214. stopKillSuggestions: function () {
  215. window.clearInterval(this.intervalId);
  216. },
  217. onKeyPress: function (e) {
  218. var that = this;
  219. // If suggestions are hidden and user presses arrow down, display suggestions:
  220. if (!that.disabled && !that.visible && e.keyCode === keys.DOWN && that.currentValue) {
  221. that.suggest();
  222. return;
  223. }
  224. if (that.disabled || !that.visible) {
  225. return;
  226. }
  227. switch (e.keyCode) {
  228. case keys.ESC:
  229. that.el.val(that.currentValue);
  230. that.hide();
  231. break;
  232. case keys.TAB:
  233. case keys.RETURN:
  234. if (that.selectedIndex === -1) {
  235. that.hide();
  236. return;
  237. }
  238. that.select(that.selectedIndex, e.keyCode === keys.RETURN);
  239. if (e.keyCode === keys.TAB && this.options.tabDisabled === false) {
  240. return;
  241. }
  242. break;
  243. case keys.UP:
  244. that.moveUp();
  245. break;
  246. case keys.DOWN:
  247. that.moveDown();
  248. break;
  249. default:
  250. return;
  251. }
  252. // Cancel event if function did not return:
  253. e.stopImmediatePropagation();
  254. e.preventDefault();
  255. },
  256. onKeyUp: function (e) {
  257. var that = this;
  258. if (that.disabled) {
  259. return;
  260. }
  261. switch (e.keyCode) {
  262. case keys.UP:
  263. case keys.DOWN:
  264. return;
  265. }
  266. clearInterval(that.onChangeInterval);
  267. if (that.currentValue !== that.el.val()) {
  268. if (that.options.deferRequestBy > 0) {
  269. // Defer lookup in case when value changes very quickly:
  270. that.onChangeInterval = setInterval(function () {
  271. that.onValueChange();
  272. }, that.options.deferRequestBy);
  273. } else {
  274. that.onValueChange();
  275. }
  276. }
  277. },
  278. onValueChange: function () {
  279. var that = this,
  280. q;
  281. clearInterval(that.onChangeInterval);
  282. that.currentValue = that.element.value;
  283. q = that.getQuery(that.currentValue);
  284. that.selectedIndex = -1;
  285. if (that.ignoreValueChange) {
  286. that.ignoreValueChange = false;
  287. return;
  288. }
  289. if (q.length < that.options.minChars) {
  290. that.hide();
  291. } else {
  292. that.getSuggestions(q);
  293. }
  294. },
  295. getQuery: function (value) {
  296. var delimiter = this.options.delimiter,
  297. parts;
  298. if (!delimiter) {
  299. return $.trim(value);
  300. }
  301. parts = value.split(delimiter);
  302. return $.trim(parts[parts.length - 1]);
  303. },
  304. getSuggestionsLocal: function (query) {
  305. var that = this,
  306. queryLowerCase = query.toLowerCase(),
  307. filter = that.options.lookupFilter;
  308. return {
  309. suggestions: $.grep(that.options.lookup, function (suggestion) {
  310. return filter(suggestion, query, queryLowerCase);
  311. })
  312. };
  313. },
  314. getSuggestions: function (q) {
  315. var response,
  316. that = this,
  317. options = that.options,
  318. serviceUrl = options.serviceUrl;
  319. response = that.isLocal ? that.getSuggestionsLocal(q) : that.cachedResponse[q];
  320. if (response && $.isArray(response.suggestions)) {
  321. that.suggestions = response.suggestions;
  322. that.suggest();
  323. } else if (!that.isBadQuery(q)) {
  324. options.params[options.paramName] = q;
  325. if (options.onSearchStart.call(that.element, options.params) === false) {
  326. return;
  327. }
  328. if ($.isFunction(options.serviceUrl)) {
  329. serviceUrl = options.serviceUrl.call(that.element, q);
  330. }
  331. $.ajax({
  332. url: serviceUrl,
  333. data: options.ignoreParams ? null : options.params,
  334. type: options.type,
  335. dataType: options.dataType
  336. }).done(function (data) {
  337. that.processResponse(data, q);
  338. options.onSearchComplete.call(that.element, q);
  339. });
  340. }
  341. },
  342. isBadQuery: function (q) {
  343. var badQueries = this.badQueries,
  344. i = badQueries.length;
  345. while (i--) {
  346. if (q.indexOf(badQueries[i]) === 0) {
  347. return true;
  348. }
  349. }
  350. return false;
  351. },
  352. hide: function () {
  353. var that = this;
  354. that.visible = false;
  355. that.selectedIndex = -1;
  356. $(that.suggestionsContainer).hide();
  357. },
  358. suggest: function () {
  359. if (this.suggestions.length === 0) {
  360. this.hide();
  361. return;
  362. }
  363. var that = this,
  364. formatResult = that.options.formatResult,
  365. value = that.getQuery(that.currentValue),
  366. className = that.classes.suggestion,
  367. classSelected = that.classes.selected,
  368. container = $(that.suggestionsContainer),
  369. html = '';
  370. // Build suggestions inner HTML:
  371. $.each(that.suggestions, function (i, suggestion) {
  372. html += '<div class="' + className + '" data-index="' + i + '">' + formatResult(suggestion, value) + '</div>';
  373. });
  374. container.html(html).show();
  375. that.visible = true;
  376. // Select first value by default:
  377. if (that.options.autoSelectFirst) {
  378. that.selectedIndex = 0;
  379. container.children().first().addClass(classSelected);
  380. }
  381. },
  382. verifySuggestionsFormat: function (suggestions) {
  383. // If suggestions is string array, convert them to supported format:
  384. if (suggestions.length && typeof suggestions[0] === 'string') {
  385. return $.map(suggestions, function (value) {
  386. return { value: value, data: null };
  387. });
  388. }
  389. return suggestions;
  390. },
  391. processResponse: function (response, originalQuery) {
  392. var that = this,
  393. options = that.options,
  394. result = options.transformResult(response, originalQuery);
  395. result.suggestions = that.verifySuggestionsFormat(result.suggestions);
  396. // Cache results if cache is not disabled:
  397. if (!options.noCache) {
  398. that.cachedResponse[result[options.paramName]] = result;
  399. if (result.suggestions.length === 0) {
  400. that.badQueries.push(result[options.paramName]);
  401. }
  402. }
  403. // Display suggestions only if returned query matches current value:
  404. if (originalQuery === that.getQuery(that.currentValue)) {
  405. that.suggestions = result.suggestions;
  406. that.suggest();
  407. }
  408. },
  409. activate: function (index) {
  410. var that = this,
  411. activeItem,
  412. selected = that.classes.selected,
  413. container = $(that.suggestionsContainer),
  414. children = container.children();
  415. container.children('.' + selected).removeClass(selected);
  416. that.selectedIndex = index;
  417. if (that.selectedIndex !== -1 && children.length > that.selectedIndex) {
  418. activeItem = children.get(that.selectedIndex);
  419. $(activeItem).addClass(selected);
  420. return activeItem;
  421. }
  422. return null;
  423. },
  424. select: function (i, shouldIgnoreNextValueChange) {
  425. var that = this,
  426. selectedValue = that.suggestions[i];
  427. if (selectedValue) {
  428. that.el.val(selectedValue);
  429. that.ignoreValueChange = shouldIgnoreNextValueChange;
  430. that.hide();
  431. that.onSelect(i);
  432. }
  433. },
  434. moveUp: function () {
  435. var that = this;
  436. if (that.selectedIndex === -1) {
  437. return;
  438. }
  439. if (that.selectedIndex === 0) {
  440. $(that.suggestionsContainer).children().first().removeClass(that.classes.selected);
  441. that.selectedIndex = -1;
  442. that.el.val(that.currentValue);
  443. return;
  444. }
  445. that.adjustScroll(that.selectedIndex - 1);
  446. },
  447. moveDown: function () {
  448. var that = this;
  449. if (that.selectedIndex === (that.suggestions.length - 1)) {
  450. return;
  451. }
  452. that.adjustScroll(that.selectedIndex + 1);
  453. },
  454. adjustScroll: function (index) {
  455. var that = this,
  456. activeItem = that.activate(index),
  457. offsetTop,
  458. upperBound,
  459. lowerBound,
  460. heightDelta = 25;
  461. if (!activeItem) {
  462. return;
  463. }
  464. offsetTop = activeItem.offsetTop;
  465. upperBound = $(that.suggestionsContainer).scrollTop();
  466. lowerBound = upperBound + that.options.maxHeight - heightDelta;
  467. if (offsetTop < upperBound) {
  468. $(that.suggestionsContainer).scrollTop(offsetTop);
  469. } else if (offsetTop > lowerBound) {
  470. $(that.suggestionsContainer).scrollTop(offsetTop - that.options.maxHeight + heightDelta);
  471. }
  472. that.el.val(that.getValue(that.suggestions[index].value));
  473. },
  474. onSelect: function (index) {
  475. var that = this,
  476. onSelectCallback = that.options.onSelect,
  477. suggestion = that.suggestions[index];
  478. that.el.val(that.getValue(suggestion.value));
  479. if ($.isFunction(onSelectCallback)) {
  480. onSelectCallback.call(that.element, suggestion);
  481. }
  482. },
  483. getValue: function (value) {
  484. var that = this,
  485. delimiter = that.options.delimiter,
  486. currentValue,
  487. parts;
  488. if (!delimiter) {
  489. return value;
  490. }
  491. currentValue = that.currentValue;
  492. parts = currentValue.split(delimiter);
  493. if (parts.length === 1) {
  494. return value;
  495. }
  496. return currentValue.substr(0, currentValue.length - parts[parts.length - 1].length) + value;
  497. },
  498. dispose: function () {
  499. var that = this;
  500. that.el.off('.autocomplete').removeData('autocomplete');
  501. that.disableKillerFn();
  502. $(that.suggestionsContainer).remove();
  503. }
  504. };
  505. // Create chainable jQuery plugin:
  506. $.fn.autocomplete = function (options, args) {
  507. var dataKey = 'autocomplete';
  508. // If function invoked without argument return
  509. // instance of the first matched element:
  510. if (arguments.length === 0) {
  511. return this.first().data(dataKey);
  512. }
  513. return this.each(function () {
  514. var inputElement = $(this),
  515. instance = inputElement.data(dataKey);
  516. if (typeof options === 'string') {
  517. if (instance && typeof instance[options] === 'function') {
  518. instance[options](args);
  519. }
  520. } else {
  521. // If instance already exists, destroy it:
  522. if (instance && instance.dispose) {
  523. instance.dispose();
  524. }
  525. instance = new Autocomplete(this, options);
  526. inputElement.data(dataKey, instance);
  527. }
  528. });
  529. };
  530. }));