jquery.autocomplete.js 21 KB

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