jquery.autocomplete.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  1. /*
  2. * jQuery Autocomplete plugin 1.1
  3. *
  4. * Copyright (c) 2009 Jörn Zaefferer
  5. *
  6. * Dual licensed under the MIT and GPL licenses:
  7. * http://www.opensource.org/licenses/mit-license.php
  8. * http://www.gnu.org/licenses/gpl.html
  9. *
  10. * Revision: $Id: jquery.autocomplete.js 15 2009-08-22 10:30:27Z joern.zaefferer $
  11. */
  12. ; (function ($) {
  13. $.fn.extend({
  14. autocomplete: function (urlOrData, options) {
  15. var isUrl = typeof urlOrData == "string";
  16. options = $.extend({}, $.Autocompleter.defaults, {
  17. url: isUrl ? urlOrData : null,
  18. data: isUrl ? null : urlOrData,
  19. delay: isUrl ? $.Autocompleter.defaults.delay : 10,
  20. max: options && !options.scroll ? 10 : 150
  21. }, options);
  22. // if highlight is set to false, replace it with a do-nothing function
  23. options.highlight = options.highlight || function (value) { return value; };
  24. // if the formatMatch option is not specified, then use formatItem for backwards compatibility
  25. options.formatMatch = options.formatMatch || options.formatItem;
  26. var sourceControl = this[0];
  27. sourceControl.setDefaultValue = function (value, textField, valueField) {
  28. $.ajax({
  29. // try to leverage ajaxQueue plugin to abort previous requests
  30. mode: "abort",
  31. // limit abortion to this input
  32. dataType: options.dataType,
  33. url: options.url,
  34. data: $.extend({
  35. q: "",
  36. limit: options.max
  37. }, {}),
  38. success: function (data) {
  39. if (data && data.length) {
  40. for (var i = 0; i < data.length; i++) {
  41. if (data[i][valueField].toString().toLowerCase() == value) {
  42. $(sourceControl).val(data[i][textField]);
  43. break;
  44. }
  45. }
  46. }
  47. }
  48. });
  49. };
  50. return this.each(function () {
  51. new $.Autocompleter(this, options);
  52. });
  53. },
  54. result: function (handler) {
  55. return this.bind("result", handler);
  56. },
  57. search: function (handler) {
  58. return this.trigger("search", [handler]);
  59. },
  60. flushCache: function () {
  61. return this.trigger("flushCache");
  62. },
  63. setOptions: function (options) {
  64. return this.trigger("setOptions", [options]);
  65. },
  66. unautocomplete: function () {
  67. return this.trigger("unautocomplete");
  68. }
  69. });
  70. $.Autocompleter = function (input, options) {
  71. var KEY = {
  72. UP: 38,
  73. DOWN: 40,
  74. DEL: 46,
  75. TAB: 9,
  76. RETURN: 13,
  77. ESC: 27,
  78. COMMA: 188,
  79. PAGEUP: 33,
  80. PAGEDOWN: 34,
  81. BACKSPACE: 8
  82. };
  83. // Create $ object for input element
  84. var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);
  85. var timeout;
  86. var previousValue = "";
  87. var cache = $.Autocompleter.Cache(options);
  88. var hasFocus = 0;
  89. var lastKeyPressCode;
  90. var config = {
  91. mouseDownOnSelect: false
  92. };
  93. var select = $.Autocompleter.Select(options, input, selectCurrent, config);
  94. var blockSubmit;
  95. // prevent form submit in opera when selecting with return key
  96. $.browser.opera && $(input.form).bind("submit.autocomplete", function () {
  97. if (blockSubmit) {
  98. blockSubmit = false;
  99. return false;
  100. }
  101. });
  102. // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
  103. $input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function (event) {
  104. // a keypress means the input has focus
  105. // avoids issue where input had focus before the autocomplete was applied
  106. hasFocus = 1;
  107. // track last key pressed
  108. lastKeyPressCode = event.keyCode;
  109. switch (event.keyCode) {
  110. case KEY.UP:
  111. event.preventDefault();
  112. if (select.visible()) {
  113. select.prev();
  114. } else {
  115. onChange(0, true);
  116. }
  117. break;
  118. case KEY.DOWN:
  119. event.preventDefault();
  120. if (select.visible()) {
  121. select.next();
  122. } else {
  123. onChange(0, true);
  124. }
  125. break;
  126. case KEY.PAGEUP:
  127. event.preventDefault();
  128. if (select.visible()) {
  129. select.pageUp();
  130. } else {
  131. onChange(0, true);
  132. }
  133. break;
  134. case KEY.PAGEDOWN:
  135. event.preventDefault();
  136. if (select.visible()) {
  137. select.pageDown();
  138. } else {
  139. onChange(0, true);
  140. }
  141. break;
  142. // matches also semicolon
  143. case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
  144. case KEY.TAB:
  145. case KEY.RETURN:
  146. if (selectCurrent()) {
  147. // stop default to prevent a form submit, Opera needs special handling
  148. event.preventDefault();
  149. blockSubmit = true;
  150. return false;
  151. }
  152. break;
  153. case KEY.ESC:
  154. select.hide();
  155. break;
  156. case KEY.BACKSPACE:
  157. if (options.Backspace) {
  158. options.Backspace();
  159. }
  160. clearTimeout(timeout);
  161. timeout = setTimeout(onChange, options.delay);
  162. break;
  163. default:
  164. // clearTimeout(timeout);
  165. // timeout = setTimeout(onChange, options.delay);
  166. break;
  167. }
  168. }).focus(function () {
  169. // track whether the field has focus, we shouldn't process any
  170. // results if the field no longer has focus
  171. hasFocus++;
  172. }).blur(function () {
  173. hasFocus = 0;
  174. if (!config.mouseDownOnSelect) {
  175. hideResults();
  176. }
  177. }).click(function () {
  178. // show select when clicking in a focused field
  179. if (hasFocus++ > 1 && !select.visible()) {
  180. onChange(0, true);
  181. }
  182. }).bind("search", function () {
  183. // TODO why not just specifying both arguments?
  184. var fn = (arguments.length > 1) ? arguments[1] : null;
  185. function findValueCallback(q, data) {
  186. var result;
  187. if (data && data.length) {
  188. for (var i = 0; i < data.length; i++) {
  189. if (data[i].result.toLowerCase() == q.toLowerCase()) {
  190. result = data[i];
  191. break;
  192. }
  193. }
  194. }
  195. if (typeof fn == "function") fn(result);
  196. else $input.trigger("result", result && [result.data, result.value]);
  197. }
  198. $.each(trimWords($input.val()), function (i, value) {
  199. request(value, findValueCallback, findValueCallback);
  200. });
  201. }).bind("flushCache", function () {
  202. cache.flush();
  203. }).bind("setOptions", function () {
  204. $.extend(options, arguments[1]);
  205. // if we've updated the data, repopulate
  206. if ("data" in arguments[1])
  207. cache.populate();
  208. }).bind("unautocomplete", function () {
  209. select.unbind();
  210. $input.unbind();
  211. $(input.form).unbind(".autocomplete");
  212. });
  213. function selectCurrent() {
  214. var selected = select.selected();
  215. if (!selected)
  216. return false;
  217. var v = selected.result;
  218. previousValue = v;
  219. if (options.multiple) {
  220. var words = trimWords($input.val());
  221. if (words.length > 1) {
  222. var seperator = options.multipleSeparator.length;
  223. var cursorAt = $(input).selection().start;
  224. var wordAt, progress = 0;
  225. $.each(words, function (i, word) {
  226. progress += word.length;
  227. if (cursorAt <= progress) {
  228. wordAt = i;
  229. return false;
  230. }
  231. progress += seperator;
  232. });
  233. words[wordAt] = v;
  234. // TODO this should set the cursor to the right position, but it gets overriden somewhere
  235. //$.Autocompleter.Selection(input, progress + seperator, progress + seperator);
  236. v = words.join(options.multipleSeparator);
  237. }
  238. v += options.multipleSeparator;
  239. }
  240. $input.val(v);
  241. hideResultsNow();
  242. $input.trigger("result", [selected.data, selected.value]);
  243. return true;
  244. }
  245. function onChange(crap, skipPrevCheck) {
  246. if (lastKeyPressCode == KEY.DEL) {
  247. select.hide();
  248. return;
  249. }
  250. var currentValue = $input.val();
  251. if (!skipPrevCheck && currentValue == previousValue)
  252. return;
  253. previousValue = currentValue;
  254. currentValue = lastWord(currentValue);
  255. if (currentValue.length >= options.minChars) {
  256. $input.addClass(options.loadingClass);
  257. if (!options.matchCase)
  258. currentValue = currentValue.toLowerCase();
  259. request(currentValue, receiveData, hideResultsNow);
  260. } else {
  261. stopLoading();
  262. select.hide();
  263. }
  264. };
  265. function trimWords(value) {
  266. if (!value)
  267. return [""];
  268. if (!options.multiple)
  269. return [$.trim(value)];
  270. return $.map(value.split(options.multipleSeparator), function (word) {
  271. return $.trim(value).length ? $.trim(word) : null;
  272. });
  273. }
  274. function lastWord(value) {
  275. if (!options.multiple)
  276. return value;
  277. var words = trimWords(value);
  278. if (words.length == 1)
  279. return words[0];
  280. var cursorAt = $(input).selection().start;
  281. if (cursorAt == value.length) {
  282. words = trimWords(value)
  283. } else {
  284. words = trimWords(value.replace(value.substring(cursorAt), ""));
  285. }
  286. return words[words.length - 1];
  287. }
  288. // fills in the input box w/the first match (assumed to be the best match)
  289. // q: the term entered
  290. // sValue: the first matching result
  291. function autoFill(q, sValue) {
  292. // autofill in the complete box w/the first match as long as the user hasn't entered in more data
  293. // if the last user key pressed was backspace, don't autofill
  294. if (options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE) {
  295. // fill in the value (keep the case the user has typed)
  296. $input.val($input.val() + sValue.substring(lastWord(previousValue).length));
  297. // select the portion of the value not typed by the user (so the next character will erase)
  298. $(input).selection(previousValue.length, previousValue.length + sValue.length);
  299. }
  300. };
  301. function hideResults() {
  302. clearTimeout(timeout);
  303. timeout = setTimeout(hideResultsNow, 200);
  304. };
  305. function hideResultsNow() {
  306. var wasVisible = select.visible();
  307. select.hide();
  308. clearTimeout(timeout);
  309. stopLoading();
  310. if (options.mustMatch) {
  311. // call search and run callback
  312. $input.search(
  313. function (result) {
  314. // if no value found, clear the input box
  315. if (!result) {
  316. if (options.multiple) {
  317. var words = trimWords($input.val()).slice(0, -1);
  318. $input.val(words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : ""));
  319. }
  320. else {
  321. $input.val("");
  322. $input.trigger("result", null);
  323. }
  324. }
  325. }
  326. );
  327. }
  328. };
  329. function receiveData(q, data) {
  330. if (data && data.length && hasFocus) {
  331. stopLoading();
  332. select.display(data, q);
  333. autoFill(q, data[0].value);
  334. select.show();
  335. } else {
  336. hideResultsNow();
  337. }
  338. };
  339. function request(term, success, failure) {
  340. if (!options.matchCase)
  341. term = term.toLowerCase();
  342. var data = cache.load(term);
  343. // recieve the cached data
  344. if (data && data.length) {
  345. success(term, data);
  346. // if an AJAX url has been supplied, try loading the data now
  347. } else if ((typeof options.url == "string") && (options.url.length > 0)) {
  348. var extraParams = {
  349. timestamp: +new Date()
  350. };
  351. $.each(options.extraParams, function (key, param) {
  352. extraParams[key] = typeof param == "function" ? param() : param;
  353. });
  354. //options.queryParamter;
  355. $.ajax({
  356. // try to leverage ajaxQueue plugin to abort previous requests
  357. mode: "abort",
  358. // limit abortion to this input
  359. port: "autocomplete" + input.name,
  360. dataType: options.dataType,
  361. url: options.url,
  362. data: $.extend({
  363. q: lastWord(term),
  364. limit: options.max
  365. }, extraParams),
  366. success: function (data) {
  367. var parsed = options.parse && options.parse(data) || parse(data);
  368. cache.add(term, parsed);
  369. success(term, parsed);
  370. }
  371. });
  372. } else {
  373. // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
  374. select.emptyList();
  375. failure(term);
  376. }
  377. };
  378. function parse(data) {
  379. var parsed = [];
  380. var rows = data.split("\n");
  381. for (var i = 0; i < rows.length; i++) {
  382. var row = $.trim(rows[i]);
  383. if (row) {
  384. row = row.split("|");
  385. parsed[parsed.length] = {
  386. data: row,
  387. value: row[0],
  388. result: options.formatResult && options.formatResult(row, row[0]) || row[0]
  389. };
  390. }
  391. }
  392. return parsed;
  393. };
  394. function stopLoading() {
  395. $input.removeClass(options.loadingClass);
  396. };
  397. };
  398. $.Autocompleter.defaults = {
  399. inputClass: "x-form-field",
  400. resultsClass: "ac_results",
  401. loadingClass: "ac_loading",
  402. minChars: 1,
  403. delay: 400,
  404. matchCase: false,
  405. matchSubset: true,
  406. matchContains: false,
  407. cacheLength: 10,
  408. valueField: "value",
  409. textField: "text",
  410. max: 100,
  411. mustMatch: false,
  412. extraParams: {},
  413. selectFirst: true,
  414. formatItem: function (row) { return row[this.textField]; },
  415. formatMatch: null,
  416. autoFill: false,
  417. width: 0,
  418. multiple: false,
  419. parse: function (data) {
  420. /*默认以Json格式*/
  421. var parsed = [];
  422. if (data && data != "") {
  423. var obj = JSON.parse(data);
  424. for (var i = 0; i < obj.length; i++) {
  425. if (obj[i]) {
  426. parsed[parsed.length] = {
  427. data: obj[i],
  428. value: obj[i][this.valueField],
  429. result: this.formatResult && this.formatResult(obj[i], obj[i]) || obj[i][this.textField]
  430. };
  431. }
  432. }
  433. }
  434. return parsed;
  435. },
  436. multipleSeparator: ", ",
  437. highlight: function (value, term) {
  438. return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
  439. },
  440. scroll: true,
  441. scrollHeight: 180
  442. };
  443. $.Autocompleter.Cache = function (options) {
  444. var data = {};
  445. var length = 0;
  446. function matchSubset(s, sub) {
  447. if (!options.matchCase)
  448. s = s.toLowerCase();
  449. var i = s.indexOf(sub);
  450. if (options.matchContains == "word") {
  451. i = s.toLowerCase().search("\\b" + sub.toLowerCase());
  452. }
  453. if (i == -1) return false;
  454. return i == 0 || options.matchContains;
  455. };
  456. function add(q, value) {
  457. if (length > options.cacheLength) {
  458. flush();
  459. }
  460. if (!data[q]) {
  461. length++;
  462. }
  463. data[q] = value;
  464. }
  465. function populate() {
  466. if (!options.data) return false;
  467. // track the matches
  468. var stMatchSets = {},
  469. nullData = 0;
  470. // no url was specified, we need to adjust the cache length to make sure it fits the local data store
  471. if (!options.url) options.cacheLength = 1;
  472. // track all options for minChars = 0
  473. stMatchSets[""] = [];
  474. // loop through the array and create a lookup structure
  475. for (var i = 0, ol = options.data.length; i < ol; i++) {
  476. var rawValue = options.data[i];
  477. // if rawValue is a string, make an array otherwise just reference the array
  478. rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;
  479. var value = options.formatMatch(rawValue, i + 1, options.data.length);
  480. if (value === false)
  481. continue;
  482. var firstChar = value.charAt(0).toLowerCase();
  483. // if no lookup array for this character exists, look it up now
  484. if (!stMatchSets[firstChar])
  485. stMatchSets[firstChar] = [];
  486. // if the match is a string
  487. var row = {
  488. value: value,
  489. data: rawValue,
  490. result: options.formatResult && options.formatResult(rawValue) || value
  491. };
  492. // push the current match into the set list
  493. stMatchSets[firstChar].push(row);
  494. // keep track of minChars zero items
  495. if (nullData++ < options.max) {
  496. stMatchSets[""].push(row);
  497. }
  498. };
  499. // add the data items to the cache
  500. $.each(stMatchSets, function (i, value) {
  501. // increase the cache size
  502. options.cacheLength++;
  503. // add to the cache
  504. add(i, value);
  505. });
  506. }
  507. // populate any existing data
  508. setTimeout(populate, 25);
  509. function flush() {
  510. data = {};
  511. length = 0;
  512. }
  513. return {
  514. flush: flush,
  515. add: add,
  516. populate: populate,
  517. load: function (q) {
  518. if (!options.cacheLength || !length)
  519. return null;
  520. /*
  521. * if dealing w/local data and matchContains than we must make sure
  522. * to loop through all the data collections looking for matches
  523. */
  524. if (!options.url && options.matchContains) {
  525. // track all matches
  526. var csub = [];
  527. // loop through all the data grids for matches
  528. for (var k in data) {
  529. // don't search through the stMatchSets[""] (minChars: 0) cache
  530. // this prevents duplicates
  531. if (k.length > 0) {
  532. var c = data[k];
  533. $.each(c, function (i, x) {
  534. // if we've got a match, add it to the array
  535. if (matchSubset(x.value, q)) {
  536. csub.push(x);
  537. }
  538. });
  539. }
  540. }
  541. return csub;
  542. } else
  543. // if the exact item exists, use it
  544. if (data[q]) {
  545. return data[q];
  546. } else
  547. if (options.matchSubset) {
  548. for (var i = q.length - 1; i >= options.minChars; i--) {
  549. var c = data[q.substr(0, i)];
  550. if (c) {
  551. var csub = [];
  552. $.each(c, function (i, x) {
  553. if (matchSubset(x.value, q)) {
  554. csub[csub.length] = x;
  555. }
  556. });
  557. return csub;
  558. }
  559. }
  560. }
  561. return null;
  562. }
  563. };
  564. };
  565. $.Autocompleter.Select = function (options, input, select, config) {
  566. var CLASSES = {
  567. ACTIVE: "ac_over"
  568. };
  569. var listItems,
  570. active = -1,
  571. data,
  572. term = "",
  573. needsInit = true,
  574. element,
  575. list;
  576. // Create results
  577. function init() {
  578. if (!needsInit)
  579. return;
  580. element = $("<div/>")
  581. .hide()
  582. .addClass(options.resultsClass)
  583. .css("position", "absolute")
  584. .appendTo(document.body);
  585. list = $("<ul/>").appendTo(element).mouseover(function (event) {
  586. if (target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
  587. active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
  588. $(target(event)).addClass(CLASSES.ACTIVE);
  589. }
  590. }).click(function (event) {
  591. $(target(event)).addClass(CLASSES.ACTIVE);
  592. select();
  593. // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
  594. input.focus();
  595. return false;
  596. }).mousedown(function () {
  597. config.mouseDownOnSelect = true;
  598. }).mouseup(function () {
  599. config.mouseDownOnSelect = false;
  600. });
  601. if (options.width > 0)
  602. element.css("width", options.width);
  603. needsInit = false;
  604. }
  605. function target(event) {
  606. var element = event.target;
  607. while (element && element.tagName != "LI")
  608. element = element.parentNode;
  609. // more fun with IE, sometimes event.target is empty, just ignore it then
  610. if (!element)
  611. return [];
  612. return element;
  613. }
  614. function moveSelect(step) {
  615. listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
  616. movePosition(step);
  617. var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
  618. if (options.scroll) {
  619. var offset = 0;
  620. listItems.slice(0, active).each(function () {
  621. offset += this.offsetHeight;
  622. });
  623. if ((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
  624. list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
  625. } else if (offset < list.scrollTop()) {
  626. list.scrollTop(offset);
  627. }
  628. }
  629. };
  630. function movePosition(step) {
  631. active += step;
  632. if (active < 0) {
  633. active = listItems.size() - 1;
  634. } else if (active >= listItems.size()) {
  635. active = 0;
  636. }
  637. }
  638. function limitNumberOfItems(available) {
  639. return options.max && options.max < available
  640. ? options.max
  641. : available;
  642. }
  643. /*填充列表*/
  644. function fillList() {
  645. list.empty();
  646. var max = limitNumberOfItems(data.length);
  647. for (var i = 0; i < max; i++) {
  648. if (!data[i])
  649. continue;
  650. var formatted = options.formatItem(data[i].data, i + 1, max, data[i].value, term);
  651. if (formatted === false)
  652. continue;
  653. var li = $("<li/>").html(options.highlight(formatted, term)).addClass(i % 2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
  654. $.data(li, "ac_data", data[i]);
  655. }
  656. listItems = list.find("li");
  657. if (options.selectFirst) {
  658. listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
  659. active = 0;
  660. }
  661. // apply bgiframe if available
  662. if ($.fn.bgiframe)
  663. list.bgiframe();
  664. }
  665. return {
  666. display: function (d, q) {
  667. init();
  668. data = d;
  669. term = q;
  670. fillList();
  671. },
  672. next: function () {
  673. moveSelect(1);
  674. },
  675. prev: function () {
  676. moveSelect(-1);
  677. },
  678. pageUp: function () {
  679. if (active != 0 && active - 8 < 0) {
  680. moveSelect(-active);
  681. } else {
  682. moveSelect(-8);
  683. }
  684. },
  685. pageDown: function () {
  686. if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
  687. moveSelect(listItems.size() - 1 - active);
  688. } else {
  689. moveSelect(8);
  690. }
  691. },
  692. hide: function () {
  693. element && element.hide();
  694. listItems && listItems.removeClass(CLASSES.ACTIVE);
  695. active = -1;
  696. },
  697. visible: function () {
  698. return element && element.is(":visible");
  699. },
  700. current: function () {
  701. return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
  702. },
  703. show: function () {
  704. var offset = $(input).offset();
  705. element.css({
  706. width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
  707. top: offset.top + input.offsetHeight,
  708. left: offset.left
  709. }).show();
  710. if (options.scroll) {
  711. list.scrollTop(0);
  712. list.css({
  713. maxHeight: options.scrollHeight,
  714. overflow: 'auto'
  715. });
  716. if ($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
  717. var listHeight = 0;
  718. listItems.each(function () {
  719. listHeight += this.offsetHeight;
  720. });
  721. var scrollbarsVisible = listHeight > options.scrollHeight;
  722. list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight);
  723. if (!scrollbarsVisible) {
  724. // IE doesn't recalculate width when scrollbar disappears
  725. listItems.width(list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")));
  726. }
  727. }
  728. }
  729. },
  730. selected: function () {
  731. var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
  732. return selected && selected.length && $.data(selected[0], "ac_data");
  733. },
  734. emptyList: function () {
  735. list && list.empty();
  736. },
  737. unbind: function () {
  738. element && element.remove();
  739. }
  740. };
  741. };
  742. $.fn.selection = function (start, end) {
  743. if (start !== undefined) {
  744. return this.each(function () {
  745. if (this.createTextRange) {
  746. var selRange = this.createTextRange();
  747. if (end === undefined || start == end) {
  748. selRange.move("character", start);
  749. selRange.select();
  750. } else {
  751. selRange.collapse(true);
  752. selRange.moveStart("character", start);
  753. selRange.moveEnd("character", end);
  754. selRange.select();
  755. }
  756. } else if (this.setSelectionRange) {
  757. this.setSelectionRange(start, end);
  758. } else if (this.selectionStart) {
  759. this.selectionStart = start;
  760. this.selectionEnd = end;
  761. }
  762. });
  763. }
  764. var field = this[0];
  765. if (field.createTextRange) {
  766. var range = document.selection.createRange(),
  767. orig = field.value,
  768. teststring = "<->",
  769. textLength = range.text.length;
  770. range.text = teststring;
  771. var caretAt = field.value.indexOf(teststring);
  772. field.value = orig;
  773. this.selection(caretAt, caretAt + textLength);
  774. return {
  775. start: caretAt,
  776. end: caretAt + textLength
  777. }
  778. } else if (field.selectionStart !== undefined) {
  779. return {
  780. start: field.selectionStart,
  781. end: field.selectionEnd
  782. }
  783. }
  784. };
  785. })(jQuery);