jquery.autocomplete.js 21 KB

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