jquery.autocomplete.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. jQuery.autocomplete = function(input, options) {
  2. // Create a link to self
  3. var me = this;
  4. var $key = null; //DF: modif
  5. // Create jQuery object for input element
  6. var $input = $(input).attr("autocomplete", "off");
  7. // Apply inputClass if necessary
  8. if (options.inputClass) $input.addClass(options.inputClass);
  9. // DF: begin modif
  10. // For combo with key/value pairs
  11. if (options.keyHolder) $key = $(options.keyHolder);
  12. // DF: end modif
  13. // Create results
  14. var results = document.createElement("div");
  15. // Create jQuery object for results
  16. var $results = $(results);
  17. $results.hide().addClass(options.resultsClass).css("position", "absolute");
  18. if( options.width > 0 ) $results.css("width", options.width);
  19. // Add to body element
  20. $("body").append(results);
  21. input.autocompleter = me;
  22. var timeout = null;
  23. var prev = "";
  24. var active = -1;
  25. var cache = {};
  26. var keyb = false;
  27. var hasFocus = false;
  28. var lastKeyPressCode = null;
  29. // flush cache
  30. function flushCache(){
  31. cache = {};
  32. cache.data = {};
  33. cache.length = 0;
  34. };
  35. // flush cache
  36. flushCache();
  37. // if there is a data array supplied
  38. if( options.data != null ){
  39. var sFirstChar = "", stMatchSets = {}, row = [];
  40. // no url was specified, we need to adjust the cache length to make sure it fits the local data store
  41. if( typeof options.url != "string" ) options.cacheLength = 1;
  42. // loop through the array and create a lookup structure
  43. for( var i=0; i < options.data.length; i++ ){
  44. // if row is a string, make an array otherwise just reference the array
  45. row = ((typeof options.data[i] == "string") ? [options.data[i]] : options.data[i]);
  46. // if the length is zero, don't add to list
  47. if( row[0].length > 0 ){
  48. // get the first character
  49. sFirstChar = row[0].substring(0, 1).toLowerCase();
  50. // if no lookup array for this character exists, look it up now
  51. if( !stMatchSets[sFirstChar] ) stMatchSets[sFirstChar] = [];
  52. // if the match is a string
  53. stMatchSets[sFirstChar].push(row);
  54. }
  55. }
  56. // add the data items to the cache
  57. for( var k in stMatchSets ){
  58. // increase the cache size
  59. options.cacheLength++;
  60. // add to the cache
  61. addToCache(k, stMatchSets[k]);
  62. }
  63. }
  64. $input
  65. .keydown(function(e) {
  66. // track last key pressed
  67. lastKeyPressCode = e.keyCode;
  68. switch(e.keyCode) {
  69. case 38: // up
  70. e.preventDefault();
  71. moveSelect(-1);
  72. break;
  73. case 40: // down
  74. e.preventDefault();
  75. moveSelect(1);
  76. break;
  77. case 9: // tab
  78. case 13: // return
  79. if( selectCurrent() ){
  80. // make sure to blur off the current field
  81. $input.get(0).blur();
  82. e.preventDefault();
  83. }
  84. break;
  85. default:
  86. active = -1;
  87. if (timeout) clearTimeout(timeout);
  88. timeout = setTimeout(function(){onChange();}, options.delay);
  89. break;
  90. }
  91. })
  92. .focus(function(){
  93. // track whether the field has focus, we shouldn't process any results if the field no longer has focus
  94. hasFocus = true;
  95. })
  96. .blur(function() {
  97. // track whether the field has focus
  98. hasFocus = false;
  99. hideResults();
  100. });
  101. hideResultsNow();
  102. function onChange() {
  103. // ignore if the following keys are pressed: [del] [shift] [capslock]
  104. if( lastKeyPressCode == 46 || (lastKeyPressCode > 8 && lastKeyPressCode < 32) ) return $results.hide();
  105. var v = $input.val();
  106. if (v == prev) return;
  107. prev = v;
  108. if (v.length >= options.minChars) {
  109. $input.addClass(options.loadingClass);
  110. requestData(v);
  111. } else {
  112. $input.removeClass(options.loadingClass);
  113. $results.hide();
  114. }
  115. };
  116. function moveSelect(step) {
  117. var lis = $("li", results);
  118. if (!lis) return;
  119. active += step;
  120. if (active < 0) {
  121. active = 0;
  122. } else if (active >= lis.size()) {
  123. active = lis.size() - 1;
  124. }
  125. lis.removeClass("ac_over");
  126. $(lis[active]).addClass("ac_over");
  127. // Weird behaviour in IE
  128. // if (lis[active] && lis[active].scrollIntoView) {
  129. // lis[active].scrollIntoView(false);
  130. // }
  131. };
  132. function selectCurrent() {
  133. var li = $("li.ac_over", results)[0];
  134. if (!li) {
  135. var $li = $("li", results);
  136. if (options.selectOnly) {
  137. if ($li.length == 1) li = $li[0];
  138. } else if (options.selectFirst) {
  139. li = $li[0];
  140. }
  141. }
  142. if (li) {
  143. selectItem(li);
  144. return true;
  145. } else {
  146. return false;
  147. }
  148. };
  149. function selectItem(li) {
  150. if (!li) {
  151. li = document.createElement("li");
  152. li.extra = [];
  153. li.selectValue = "";
  154. }
  155. var v = $.trim(li.selectValue ? li.selectValue : li.innerHTML);
  156. input.lastSelected = v;
  157. prev = v;
  158. $results.html("");
  159. $input.val(v);
  160. // DF: begin modif
  161. if ($key)
  162. {
  163. $key.val(li.extra[0]);
  164. }
  165. // DF: end modif
  166. hideResultsNow();
  167. if (options.onItemSelect) setTimeout(function() { options.onItemSelect(li) }, 1);
  168. };
  169. // selects a portion of the input string
  170. function createSelection(start, end){
  171. // get a reference to the input element
  172. var field = $input.get(0);
  173. if( field.createTextRange ){
  174. var selRange = field.createTextRange();
  175. selRange.collapse(true);
  176. selRange.moveStart("character", start);
  177. selRange.moveEnd("character", end);
  178. selRange.select();
  179. } else if( field.setSelectionRange ){
  180. field.setSelectionRange(start, end);
  181. } else {
  182. if( field.selectionStart ){
  183. field.selectionStart = start;
  184. field.selectionEnd = end;
  185. }
  186. }
  187. field.focus();
  188. };
  189. // fills in the input box w/the first match (assumed to be the best match)
  190. function autoFill(sValue){
  191. // if the last user key pressed was backspace, don't autofill
  192. if( lastKeyPressCode != 8 ){
  193. // fill in the value (keep the case the user has typed)
  194. $input.val($input.val() + sValue.substring(prev.length));
  195. // select the portion of the value not typed by the user (so the next character will erase)
  196. createSelection(prev.length, sValue.length);
  197. }
  198. };
  199. function showResults() {
  200. // get the position of the input field right now (in case the DOM is shifted)
  201. var pos = findPos(input);
  202. // either use the specified width, or autocalculate based on form element
  203. var iWidth = (options.width > 0) ? options.width : $input.width();
  204. // reposition
  205. $results.css({
  206. width: parseInt(iWidth) + "px",
  207. top: (pos.y + input.offsetHeight) + "px",
  208. left: pos.x + "px"
  209. }).show();
  210. };
  211. function hideResults() {
  212. if (timeout) clearTimeout(timeout);
  213. timeout = setTimeout(hideResultsNow, 200);
  214. };
  215. function hideResultsNow() {
  216. if (timeout) clearTimeout(timeout);
  217. $input.removeClass(options.loadingClass);
  218. if ($results.is(":visible")) {
  219. $results.hide();
  220. }
  221. if (options.mustMatch) {
  222. var v = $input.val();
  223. if (v != input.lastSelected) {
  224. selectItem(null);
  225. }
  226. }
  227. };
  228. function receiveData(q, data) {
  229. if (data) {
  230. $input.removeClass(options.loadingClass);
  231. results.innerHTML = "";
  232. // if the field no longer has focus or if there are no matches, do not display the drop down
  233. if( !hasFocus || data.length == 0 ) return hideResultsNow();
  234. if ($.browser.msie) {
  235. // we put a styled iframe behind the calendar so HTML SELECT elements don't show through
  236. $results.append(document.createElement('iframe'));
  237. }
  238. results.appendChild(dataToDom(data));
  239. // autofill in the complete box w/the first match as long as the user hasn't entered in more data
  240. if( options.autoFill && ($input.val().toLowerCase() == q.toLowerCase()) ) autoFill(data[0][0]);
  241. showResults();
  242. } else {
  243. hideResultsNow();
  244. }
  245. };
  246. function parseData(data) {
  247. if (!data) return null;
  248. var parsed = [];
  249. var rows = data.split(options.lineSeparator);
  250. for (var i=0; i < rows.length; i++) {
  251. var row = $.trim(rows[i]);
  252. if (row) {
  253. parsed[parsed.length] = row.split(options.cellSeparator);
  254. }
  255. }
  256. return parsed;
  257. };
  258. function dataToDom(data) {
  259. var ul = document.createElement("ul");
  260. var num = data.length;
  261. // limited results to a max number
  262. if( (options.maxItemsToShow > 0) && (options.maxItemsToShow < num) ) num = options.maxItemsToShow;
  263. for (var i=0; i < num; i++) {
  264. var row = data[i];
  265. if (!row) continue;
  266. var li = document.createElement("li");
  267. if (options.formatItem) {
  268. li.innerHTML = options.formatItem(row, i, num);
  269. li.selectValue = row[0];
  270. } else {
  271. li.innerHTML = row[0];
  272. li.selectValue = row[0];
  273. }
  274. var extra = null;
  275. if (row.length > 1) {
  276. extra = [];
  277. for (var j=1; j < row.length; j++) {
  278. extra[extra.length] = row[j];
  279. }
  280. }
  281. li.extra = extra;
  282. ul.appendChild(li);
  283. $(li).hover(
  284. function() { $("li", ul).removeClass("ac_over"); $(this).addClass("ac_over"); active = $("li", ul).indexOf($(this).get(0)); },
  285. function() { $(this).removeClass("ac_over"); }
  286. ).click(function(e) { e.preventDefault(); e.stopPropagation(); selectItem(this) });
  287. }
  288. return ul;
  289. };
  290. function requestData(q) {
  291. if (!options.matchCase) q = q.toLowerCase();
  292. var data = options.cacheLength ? loadFromCache(q) : null;
  293. // recieve the cached data
  294. if (data) {
  295. receiveData(q, data);
  296. // if an AJAX url has been supplied, try loading the data now
  297. } else if( (typeof options.url == "string") && (options.url.length > 0) ){
  298. $.get(makeUrl(q), function(data) {
  299. data = parseData(data);
  300. addToCache(q, data);
  301. receiveData(q, data);
  302. });
  303. // if there's been no data found, remove the loading class
  304. } else {
  305. $input.removeClass(options.loadingClass);
  306. }
  307. };
  308. function makeUrl(q) {
  309. var url = options.url + "?q=" + encodeURI(q);
  310. for (var i in options.extraParams) {
  311. url += "&" + i + "=" + encodeURI(options.extraParams[i]);
  312. }
  313. return url;
  314. };
  315. function loadFromCache(q) {
  316. if (!q) return null;
  317. if (cache.data[q]) return cache.data[q];
  318. if (options.matchSubset) {
  319. for (var i = q.length - 1; i >= options.minChars; i--) {
  320. var qs = q.substr(0, i);
  321. var c = cache.data[qs];
  322. if (c) {
  323. var csub = [];
  324. for (var j = 0; j < c.length; j++) {
  325. var x = c[j];
  326. var x0 = x[0];
  327. if (matchSubset(x0, q)) {
  328. csub[csub.length] = x;
  329. }
  330. }
  331. return csub;
  332. }
  333. }
  334. }
  335. return null;
  336. };
  337. function matchSubset(s, sub) {
  338. if (!options.matchCase) s = s.toLowerCase();
  339. var i = s.indexOf(sub);
  340. if (i == -1) return false;
  341. return i == 0 || options.matchContains;
  342. };
  343. this.flushCache = function() {
  344. flushCache();
  345. };
  346. this.setExtraParams = function(p) {
  347. options.extraParams = p;
  348. };
  349. this.findValue = function(){
  350. var q = $input.val();
  351. if (!options.matchCase) q = q.toLowerCase();
  352. var data = options.cacheLength ? loadFromCache(q) : null;
  353. if (data) {
  354. findValueCallback(q, data);
  355. } else if( (typeof options.url == "string") && (options.url.length > 0) ){
  356. $.get(makeUrl(q), function(data) {
  357. data = parseData(data)
  358. addToCache(q, data);
  359. findValueCallback(q, data);
  360. });
  361. } else {
  362. // no matches
  363. findValueCallback(q, null);
  364. }
  365. }
  366. function findValueCallback(q, data){
  367. if (data) $input.removeClass(options.loadingClass);
  368. var num = (data) ? data.length : 0;
  369. var li = null;
  370. for (var i=0; i < num; i++) {
  371. var row = data[i];
  372. if( row[0].toLowerCase() == q.toLowerCase() ){
  373. li = document.createElement("li");
  374. if (options.formatItem) {
  375. li.innerHTML = options.formatItem(row, i, num);
  376. li.selectValue = row[0];
  377. } else {
  378. li.innerHTML = row[0];
  379. }
  380. var extra = null;
  381. if( row.length > 1 ){
  382. extra = [];
  383. for (var j=1; j < row.length; j++) {
  384. extra[extra.length] = row[j];
  385. }
  386. }
  387. li.extra = extra;
  388. }
  389. }
  390. if( options.onFindValue ) setTimeout(function() { options.onFindValue(li) }, 1);
  391. }
  392. function addToCache(q, data) {
  393. if (!data || !q || !options.cacheLength) return;
  394. if (!cache.length || cache.length > options.cacheLength) {
  395. flushCache();
  396. cache.length++;
  397. } else if (!cache[q]) {
  398. cache.length++;
  399. }
  400. cache.data[q] = data;
  401. };
  402. function findPos(obj) {
  403. var curleft = obj.offsetLeft || 0;
  404. var curtop = obj.offsetTop || 0;
  405. while (obj = obj.offsetParent) {
  406. curleft += obj.offsetLeft
  407. curtop += obj.offsetTop
  408. }
  409. return {x:curleft,y:curtop};
  410. }
  411. }
  412. jQuery.fn.autocomplete = function(url, options, data) {
  413. // Make sure options exists
  414. options = options || {};
  415. // Set url as option
  416. options.url = url;
  417. // set some bulk local data
  418. options.data = ((typeof data == "object") && (data.constructor == Array)) ? data : null;
  419. // Set default values for required options
  420. options.inputClass = options.inputClass || "ac_input";
  421. options.resultsClass = options.resultsClass || "ac_results";
  422. options.lineSeparator = options.lineSeparator || "\n";
  423. options.cellSeparator = options.cellSeparator || "|";
  424. options.minChars = options.minChars || 1;
  425. options.delay = options.delay || 400;
  426. options.matchCase = options.matchCase || 0;
  427. options.matchSubset = options.matchSubset || 1;
  428. options.matchContains = options.matchContains || 0;
  429. options.cacheLength = options.cacheLength || 1;
  430. options.mustMatch = options.mustMatch || 0;
  431. options.extraParams = options.extraParams || {};
  432. options.loadingClass = options.loadingClass || "ac_loading";
  433. options.selectFirst = options.selectFirst || false;
  434. options.selectOnly = options.selectOnly || false;
  435. options.maxItemsToShow = options.maxItemsToShow || -1;
  436. options.autoFill = options.autoFill || false;
  437. options.width = parseInt(options.width, 10) || 0;
  438. this.each(function() {
  439. var input = this;
  440. new jQuery.autocomplete(input, options);
  441. });
  442. // Don't break the chain
  443. return this;
  444. }
  445. jQuery.fn.autocompleteArray = function(data, options) {
  446. return this.autocomplete(null, options, data);
  447. }
  448. jQuery.fn.indexOf = function(e){
  449. for( var i=0; i<this.length; i++ ){
  450. if( this[i] == e ) return i;
  451. }
  452. return -1;
  453. };