jquery.autocomplete.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  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,v 1.3 2013/08/31 07:45:17 wengsibo Exp $
  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. }).bind("input", function() {
  182. // @hack by xuesong:firefox中文输入支持
  183. onChange(0, true);
  184. });
  185. function selectCurrent() {
  186. var selected = select.selected();
  187. if( !selected )
  188. return false;
  189. var v = selected.result;
  190. previousValue = v;
  191. if ( options.multiple ) {
  192. var words = trimWords($input.val());
  193. if ( words.length > 1 ) {
  194. var seperator = options.multipleSeparator.length;
  195. var cursorAt = $(input).selection().start;
  196. var wordAt, progress = 0;
  197. $.each(words, function(i, word) {
  198. progress += word.length;
  199. if (cursorAt <= progress) {
  200. wordAt = i;
  201. return false;
  202. }
  203. progress += seperator;
  204. });
  205. words[wordAt] = v;
  206. // TODO this should set the cursor to the right position, but it gets overriden somewhere
  207. //$.Autocompleter.Selection(input, progress + seperator, progress + seperator);
  208. v = words.join( options.multipleSeparator );
  209. }
  210. v += options.multipleSeparator;
  211. }
  212. $input.val(v);
  213. hideResultsNow();
  214. $input.trigger("result", [selected.data, selected.value]);
  215. return true;
  216. }
  217. function onChange(crap, skipPrevCheck) {
  218. if( lastKeyPressCode == KEY.DEL ) {
  219. select.hide();
  220. return;
  221. }
  222. var currentValue = $input.val();
  223. if ( !skipPrevCheck && currentValue == previousValue )
  224. return;
  225. previousValue = currentValue;
  226. currentValue = lastWord(currentValue);
  227. if ( currentValue.length >= options.minChars) {
  228. $input.addClass(options.loadingClass);
  229. if (!options.matchCase)
  230. currentValue = currentValue.toLowerCase();
  231. request(currentValue, receiveData, hideResultsNow);
  232. } else {
  233. stopLoading();
  234. select.hide();
  235. }
  236. };
  237. function trimWords(value) {
  238. if (!value)
  239. return [""];
  240. if (!options.multiple)
  241. return [$.trim(value)];
  242. return $.map(value.split(options.multipleSeparator), function(word) {
  243. return $.trim(value).length ? $.trim(word) : null;
  244. });
  245. }
  246. function lastWord(value) {
  247. if ( !options.multiple )
  248. return value;
  249. var words = trimWords(value);
  250. if (words.length == 1)
  251. return words[0];
  252. var cursorAt = $(input).selection().start;
  253. if (cursorAt == value.length) {
  254. words = trimWords(value)
  255. } else {
  256. words = trimWords(value.replace(value.substring(cursorAt), ""));
  257. }
  258. return words[words.length - 1];
  259. }
  260. // fills in the input box w/the first match (assumed to be the best match)
  261. // q: the term entered
  262. // sValue: the first matching result
  263. function autoFill(q, sValue){
  264. // autofill in the complete box w/the first match as long as the user hasn't entered in more data
  265. // if the last user key pressed was backspace, don't autofill
  266. if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {
  267. // fill in the value (keep the case the user has typed)
  268. $input.val($input.val() + sValue.substring(lastWord(previousValue).length));
  269. // select the portion of the value not typed by the user (so the next character will erase)
  270. $(input).selection(previousValue.length, previousValue.length + sValue.length);
  271. }
  272. };
  273. function hideResults() {
  274. clearTimeout(timeout);
  275. timeout = setTimeout(hideResultsNow, 200);
  276. };
  277. function hideResultsNow() {
  278. var wasVisible = select.visible();
  279. select.hide();
  280. clearTimeout(timeout);
  281. stopLoading();
  282. if (options.mustMatch) {
  283. // call search and run callback
  284. $input.search(
  285. function (result){
  286. // if no value found, clear the input box
  287. if( !result ) {
  288. if (options.multiple) {
  289. var words = trimWords($input.val()).slice(0, -1);
  290. $input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
  291. }
  292. else {
  293. $input.val( "" );
  294. $input.trigger("result", null);
  295. }
  296. }
  297. }
  298. );
  299. }
  300. };
  301. function receiveData(q, data) {
  302. if ( data && data.length && hasFocus ) {
  303. stopLoading();
  304. select.display(data, q);
  305. autoFill(q, data[0].value);
  306. select.show();
  307. } else {
  308. hideResultsNow();
  309. }
  310. };
  311. function request(term, success, failure) {
  312. if (!options.matchCase)
  313. term = term.toLowerCase();
  314. var data = cache.load(term);
  315. // recieve the cached data
  316. if (data && data.length) {
  317. success(term, data);
  318. // if an AJAX url has been supplied, try loading the data now
  319. } else if( (typeof options.url == "string") && (options.url.length > 0) ){
  320. var extraParams = {
  321. timestamp: +new Date()
  322. };
  323. $.each(options.extraParams, function(key, param) {
  324. extraParams[key] = typeof param == "function" ? param() : param;
  325. });
  326. $.ajax({
  327. // try to leverage ajaxQueue plugin to abort previous requests
  328. mode: "abort",
  329. // limit abortion to this input
  330. port: "autocomplete" + input.name,
  331. dataType: options.dataType,
  332. url: options.url,
  333. data: $.extend({
  334. q: lastWord(term),
  335. limit: options.max
  336. }, extraParams),
  337. success: function(data) {
  338. var parsed = options.parse && options.parse(data) || parse(data);
  339. cache.add(term, parsed);
  340. success(term, parsed);
  341. }
  342. });
  343. } else {
  344. // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
  345. select.emptyList();
  346. failure(term);
  347. }
  348. };
  349. function parse(data) {
  350. var parsed = [];
  351. var rows = data.split("\n");
  352. for (var i=0; i < rows.length; i++) {
  353. var row = $.trim(rows[i]);
  354. if (row) {
  355. row = row.split("|");
  356. parsed[parsed.length] = {
  357. data: row,
  358. value: row[0],
  359. result: options.formatResult && options.formatResult(row, row[0]) || row[0]
  360. };
  361. }
  362. }
  363. return parsed;
  364. };
  365. function stopLoading() {
  366. $input.removeClass(options.loadingClass);
  367. };
  368. };
  369. $.Autocompleter.defaults = {
  370. inputClass: "ac_input",
  371. resultsClass: "ac_results",
  372. loadingClass: "ac_loading",
  373. minChars: 1,
  374. delay: 400,
  375. matchCase: false,
  376. matchSubset: true,
  377. matchContains: false,
  378. cacheLength: 10,
  379. max: 100,
  380. mustMatch: false,
  381. extraParams: {},
  382. selectFirst: true,
  383. formatItem: function(row) { return row[0]; },
  384. formatMatch: null,
  385. autoFill: false,
  386. width: 0,
  387. multiple: false,
  388. multipleSeparator: ", ",
  389. highlight: function(value, term) {
  390. return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
  391. },
  392. scroll: true,
  393. scrollHeight: 180
  394. };
  395. $.Autocompleter.Cache = function(options) {
  396. var data = {};
  397. var length = 0;
  398. function matchSubset(s, sub) {
  399. if (!options.matchCase)
  400. s = s.toLowerCase();
  401. var i = s.indexOf(sub);
  402. if (options.matchContains == "word"){
  403. i = s.toLowerCase().search("\\b" + sub.toLowerCase());
  404. }
  405. if (i == -1) return false;
  406. return i == 0 || options.matchContains;
  407. };
  408. function add(q, value) {
  409. if (length > options.cacheLength){
  410. flush();
  411. }
  412. if (!data[q]){
  413. length++;
  414. }
  415. data[q] = value;
  416. }
  417. function populate(){
  418. if( !options.data ) return false;
  419. // track the matches
  420. var stMatchSets = {},
  421. nullData = 0;
  422. // no url was specified, we need to adjust the cache length to make sure it fits the local data store
  423. if( !options.url ) options.cacheLength = 1;
  424. // track all options for minChars = 0
  425. stMatchSets[""] = [];
  426. // loop through the array and create a lookup structure
  427. for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
  428. var rawValue = options.data[i];
  429. // if rawValue is a string, make an array otherwise just reference the array
  430. rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;
  431. var value = options.formatMatch(rawValue, i+1, options.data.length);
  432. if ( value === false )
  433. continue;
  434. var firstChar = value.charAt(0).toLowerCase();
  435. // if no lookup array for this character exists, look it up now
  436. if( !stMatchSets[firstChar] )
  437. stMatchSets[firstChar] = [];
  438. // if the match is a string
  439. var row = {
  440. value: value,
  441. data: rawValue,
  442. result: options.formatResult && options.formatResult(rawValue) || value
  443. };
  444. // push the current match into the set list
  445. stMatchSets[firstChar].push(row);
  446. // keep track of minChars zero items
  447. if ( nullData++ < options.max ) {
  448. stMatchSets[""].push(row);
  449. }
  450. };
  451. // add the data items to the cache
  452. $.each(stMatchSets, function(i, value) {
  453. // increase the cache size
  454. options.cacheLength++;
  455. // add to the cache
  456. add(i, value);
  457. });
  458. }
  459. // populate any existing data
  460. setTimeout(populate, 25);
  461. function flush(){
  462. data = {};
  463. length = 0;
  464. }
  465. return {
  466. flush: flush,
  467. add: add,
  468. populate: populate,
  469. load: function(q) {
  470. if (!options.cacheLength || !length)
  471. return null;
  472. /*
  473. * if dealing w/local data and matchContains than we must make sure
  474. * to loop through all the data collections looking for matches
  475. */
  476. if( !options.url && options.matchContains ){
  477. // track all matches
  478. var csub = [];
  479. // loop through all the data grids for matches
  480. for( var k in data ){
  481. // don't search through the stMatchSets[""] (minChars: 0) cache
  482. // this prevents duplicates
  483. if( k.length > 0 ){
  484. var c = data[k];
  485. $.each(c, function(i, x) {
  486. // if we've got a match, add it to the array
  487. if (matchSubset(x.value, q)) {
  488. csub.push(x);
  489. }
  490. });
  491. }
  492. }
  493. return csub;
  494. } else
  495. // if the exact item exists, use it
  496. if (data[q]){
  497. return data[q];
  498. } else
  499. if (options.matchSubset) {
  500. for (var i = q.length - 1; i >= options.minChars; i--) {
  501. var c = data[q.substr(0, i)];
  502. if (c) {
  503. var csub = [];
  504. $.each(c, function(i, x) {
  505. if (matchSubset(x.value, q)) {
  506. csub[csub.length] = x;
  507. }
  508. });
  509. return csub;
  510. }
  511. }
  512. }
  513. return null;
  514. }
  515. };
  516. };
  517. $.Autocompleter.Select = function (options, input, select, config) {
  518. var CLASSES = {
  519. ACTIVE: "ac_over"
  520. };
  521. var listItems,
  522. active = -1,
  523. data,
  524. term = "",
  525. needsInit = true,
  526. element,
  527. list;
  528. // Create results
  529. function init() {
  530. if (!needsInit)
  531. return;
  532. element = $("<div/>")
  533. .hide()
  534. .addClass(options.resultsClass)
  535. .css("position", "absolute")
  536. .appendTo(document.body);
  537. list = $("<ul/>").appendTo(element).mouseover( function(event) {
  538. if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
  539. active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
  540. $(target(event)).addClass(CLASSES.ACTIVE);
  541. }
  542. }).click(function(event) {
  543. $(target(event)).addClass(CLASSES.ACTIVE);
  544. select();
  545. // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
  546. input.focus();
  547. return false;
  548. }).mousedown(function() {
  549. config.mouseDownOnSelect = true;
  550. }).mouseup(function() {
  551. config.mouseDownOnSelect = false;
  552. });
  553. if( options.width > 0 )
  554. element.css("width", options.width);
  555. needsInit = false;
  556. }
  557. function target(event) {
  558. var element = event.target;
  559. while(element && element.tagName != "LI")
  560. element = element.parentNode;
  561. // more fun with IE, sometimes event.target is empty, just ignore it then
  562. if(!element)
  563. return [];
  564. return element;
  565. }
  566. function moveSelect(step) {
  567. listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
  568. movePosition(step);
  569. var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
  570. if(options.scroll) {
  571. var offset = 0;
  572. listItems.slice(0, active).each(function() {
  573. offset += this.offsetHeight;
  574. });
  575. if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
  576. list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
  577. } else if(offset < list.scrollTop()) {
  578. list.scrollTop(offset);
  579. }
  580. }
  581. };
  582. function movePosition(step) {
  583. active += step;
  584. if (active < 0) {
  585. active = listItems.size() - 1;
  586. } else if (active >= listItems.size()) {
  587. active = 0;
  588. }
  589. }
  590. function limitNumberOfItems(available) {
  591. return options.max && options.max < available
  592. ? options.max
  593. : available;
  594. }
  595. function fillList() {
  596. list.empty();
  597. var max = limitNumberOfItems(data.length);
  598. for (var i=0; i < max; i++) {
  599. if (!data[i])
  600. continue;
  601. var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
  602. if ( formatted === false )
  603. continue;
  604. var li = $("<li/>").html( options.highlight(formatted, term) ).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. var topss1 = $(document).scrollTop();
  657. element.css({
  658. width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
  659. top: offset.top + input.offsetHeight-topss1,
  660. //top:input.offsetHeight,
  661. left: offset.left
  662. }).show();
  663. if(options.scroll) {
  664. list.scrollTop(0);
  665. list.css({
  666. maxHeight: options.scrollHeight,
  667. overflow: 'auto'
  668. });
  669. if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
  670. var listHeight = 0;
  671. listItems.each(function() {
  672. listHeight += this.offsetHeight;
  673. });
  674. var scrollbarsVisible = listHeight > options.scrollHeight;
  675. list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
  676. if (!scrollbarsVisible) {
  677. // IE doesn't recalculate width when scrollbar disappears
  678. listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
  679. }
  680. }
  681. }
  682. },
  683. selected: function() {
  684. var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
  685. return selected && selected.length && $.data(selected[0], "ac_data");
  686. },
  687. emptyList: function (){
  688. list && list.empty();
  689. },
  690. unbind: function() {
  691. element && element.remove();
  692. }
  693. };
  694. };
  695. $.fn.selection = function(start, end) {
  696. if (start !== undefined) {
  697. return this.each(function() {
  698. if( this.createTextRange ){
  699. var selRange = this.createTextRange();
  700. if (end === undefined || start == end) {
  701. selRange.move("character", start);
  702. selRange.select();
  703. } else {
  704. selRange.collapse(true);
  705. selRange.moveStart("character", start);
  706. selRange.moveEnd("character", end);
  707. selRange.select();
  708. }
  709. } else if( this.setSelectionRange ){
  710. this.setSelectionRange(start, end);
  711. } else if( this.selectionStart ){
  712. this.selectionStart = start;
  713. this.selectionEnd = end;
  714. }
  715. });
  716. }
  717. var field = this[0];
  718. if ( field.createTextRange ) {
  719. var range = document.selection.createRange(),
  720. orig = field.value,
  721. teststring = "<->",
  722. textLength = range.text.length;
  723. range.text = teststring;
  724. var caretAt = field.value.indexOf(teststring);
  725. field.value = orig;
  726. this.selection(caretAt, caretAt + textLength);
  727. return {
  728. start: caretAt,
  729. end: caretAt + textLength
  730. }
  731. } else if( field.selectionStart !== undefined ){
  732. return {
  733. start: field.selectionStart,
  734. end: field.selectionEnd
  735. }
  736. }
  737. };
  738. })(jQuery);