jquery.autocomplete.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. /*
  2. * jQuery Autocomplete plugin 1.1
  3. *
  4. * Copyright (c) 2009 Jorn 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. // limit abortion to this input
  327. port: "autocomplete" + input.name,
  328. dataType: options.dataType,
  329. url: options.url,
  330. data: $.extend({
  331. q: lastWord(term),
  332. limit: options.max
  333. }, extraParams),
  334. success: function(data) {
  335. var parsed = options.parse && options.parse(data) || parse(data);
  336. cache.add(term, parsed);
  337. success(term, parsed);
  338. }
  339. });
  340. } else {
  341. // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
  342. select.emptyList();
  343. failure(term);
  344. }
  345. };
  346. function parse(data) {
  347. var parsed = [];
  348. var rows = data.split("\n");
  349. for (var i=0; i < rows.length; i++) {
  350. var row = $.trim(rows[i]);
  351. if (row) {
  352. row = row.split("|");
  353. parsed[parsed.length] = {
  354. data: row,
  355. value: row[0],
  356. result: options.formatResult && options.formatResult(row, row[0]) || row[0]
  357. };
  358. }
  359. }
  360. return parsed;
  361. };
  362. function stopLoading() {
  363. $input.removeClass(options.loadingClass);
  364. };
  365. };
  366. $.Autocompleter.defaults = {
  367. inputClass: "ac_input",
  368. resultsClass: "ac_results",
  369. loadingClass: "ac_loading",
  370. minChars: 1,
  371. delay: 400,
  372. matchCase: false,
  373. matchSubset: true,
  374. matchContains: false,
  375. cacheLength: 10,
  376. max: 100,
  377. mustMatch: false,
  378. extraParams: {},
  379. selectFirst: true,
  380. formatItem: function(row) { return row[0]; },
  381. formatMatch: null,
  382. autoFill: false,
  383. width: 0,
  384. multiple: false,
  385. multipleSeparator: ", ",
  386. highlight: function(value, term) {
  387. return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
  388. },
  389. scroll: true,
  390. scrollHeight: 180
  391. };
  392. $.Autocompleter.Cache = function(options) {
  393. var data = {};
  394. var length = 0;
  395. function matchSubset(s, sub) {
  396. if (!options.matchCase)
  397. s = s.toLowerCase();
  398. var i = s.indexOf(sub);
  399. if (options.matchContains == "word"){
  400. i = s.toLowerCase().search("\\b" + sub.toLowerCase());
  401. }
  402. if (i == -1) return false;
  403. return i == 0 || options.matchContains;
  404. };
  405. function add(q, value) {
  406. if (length > options.cacheLength){
  407. flush();
  408. }
  409. if (!data[q]){
  410. length++;
  411. }
  412. data[q] = value;
  413. }
  414. function populate(){
  415. if( !options.data ) return false;
  416. // track the matches
  417. var stMatchSets = {},
  418. nullData = 0;
  419. // no url was specified, we need to adjust the cache length to make sure it fits the local data store
  420. if( !options.url ) options.cacheLength = 1;
  421. // track all options for minChars = 0
  422. stMatchSets[""] = [];
  423. // loop through the array and create a lookup structure
  424. for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
  425. var rawValue = options.data[i];
  426. // if rawValue is a string, make an array otherwise just reference the array
  427. rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;
  428. var value = options.formatMatch(rawValue, i+1, options.data.length);
  429. if ( value === false )
  430. continue;
  431. var firstChar = value.charAt(0).toLowerCase();
  432. // if no lookup array for this character exists, look it up now
  433. if( !stMatchSets[firstChar] )
  434. stMatchSets[firstChar] = [];
  435. // if the match is a string
  436. var row = {
  437. value: value,
  438. data: rawValue,
  439. result: options.formatResult && options.formatResult(rawValue) || value
  440. };
  441. // push the current match into the set list
  442. stMatchSets[firstChar].push(row);
  443. // keep track of minChars zero items
  444. if ( nullData++ < options.max ) {
  445. stMatchSets[""].push(row);
  446. }
  447. };
  448. // add the data items to the cache
  449. $.each(stMatchSets, function(i, value) {
  450. // increase the cache size
  451. options.cacheLength++;
  452. // add to the cache
  453. add(i, value);
  454. });
  455. }
  456. // populate any existing data
  457. setTimeout(populate, 25);
  458. function flush(){
  459. data = {};
  460. length = 0;
  461. }
  462. return {
  463. flush: flush,
  464. add: add,
  465. populate: populate,
  466. load: function(q) {
  467. if (!options.cacheLength || !length)
  468. return null;
  469. /*
  470. * if dealing w/local data and matchContains than we must make sure
  471. * to loop through all the data collections looking for matches
  472. */
  473. if( !options.url && options.matchContains ){
  474. // track all matches
  475. var csub = [];
  476. // loop through all the data grids for matches
  477. for( var k in data ){
  478. // don't search through the stMatchSets[""] (minChars: 0) cache
  479. // this prevents duplicates
  480. if( k.length > 0 ){
  481. var c = data[k];
  482. $.each(c, function(i, x) {
  483. // if we've got a match, add it to the array
  484. if (matchSubset(x.value, q)) {
  485. csub.push(x);
  486. }
  487. });
  488. }
  489. }
  490. return csub;
  491. } else
  492. // if the exact item exists, use it
  493. if (data[q]){
  494. return data[q];
  495. } else
  496. if (options.matchSubset) {
  497. for (var i = q.length - 1; i >= options.minChars; i--) {
  498. var c = data[q.substr(0, i)];
  499. if (c) {
  500. var csub = [];
  501. $.each(c, function(i, x) {
  502. if (matchSubset(x.value, q)) {
  503. csub[csub.length] = x;
  504. }
  505. });
  506. return csub;
  507. }
  508. }
  509. }
  510. return null;
  511. }
  512. };
  513. };
  514. $.Autocompleter.Select = function (options, input, select, config) {
  515. var CLASSES = {
  516. ACTIVE: "ac_over"
  517. };
  518. var listItems,
  519. active = -1,
  520. data,
  521. term = "",
  522. needsInit = true,
  523. element,
  524. list;
  525. // Create results
  526. function init() {
  527. if (!needsInit)
  528. return;
  529. element = $("<div/>")
  530. .hide()
  531. .addClass(options.resultsClass)
  532. .css("position", "absolute")
  533. .appendTo(document.body);
  534. list = $("<ul/>").appendTo(element).mouseover( function(event) {
  535. if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
  536. active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
  537. $(target(event)).addClass(CLASSES.ACTIVE);
  538. }
  539. }).click(function(event) {
  540. $(target(event)).addClass(CLASSES.ACTIVE);
  541. select();
  542. // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
  543. input.focus();
  544. return false;
  545. }).mousedown(function() {
  546. config.mouseDownOnSelect = true;
  547. }).mouseup(function() {
  548. config.mouseDownOnSelect = false;
  549. });
  550. if( options.width > 0 )
  551. element.css("width", options.width);
  552. needsInit = false;
  553. }
  554. function target(event) {
  555. var element = event.target;
  556. while(element && element.tagName != "LI")
  557. element = element.parentNode;
  558. // more fun with IE, sometimes event.target is empty, just ignore it then
  559. if(!element)
  560. return [];
  561. return element;
  562. }
  563. function moveSelect(step) {
  564. listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
  565. movePosition(step);
  566. var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
  567. if(options.scroll) {
  568. var offset = 0;
  569. listItems.slice(0, active).each(function() {
  570. offset += this.offsetHeight;
  571. });
  572. if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
  573. list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
  574. } else if(offset < list.scrollTop()) {
  575. list.scrollTop(offset);
  576. }
  577. }
  578. };
  579. function movePosition(step) {
  580. active += step;
  581. if (active < 0) {
  582. active = listItems.size() - 1;
  583. } else if (active >= listItems.size()) {
  584. active = 0;
  585. }
  586. }
  587. function limitNumberOfItems(available) {
  588. return options.max && options.max < available
  589. ? options.max
  590. : available;
  591. }
  592. function fillList() {
  593. list.empty();
  594. var max = limitNumberOfItems(data.length);
  595. for (var i=0; i < max; i++) {
  596. if (!data[i])
  597. continue;
  598. var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
  599. if ( formatted === false )
  600. continue;
  601. var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
  602. $.data(li, "ac_data", data[i]);
  603. }
  604. listItems = list.find("li");
  605. if ( options.selectFirst ) {
  606. listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
  607. active = 0;
  608. }
  609. // apply bgiframe if available
  610. if ( $.fn.bgiframe )
  611. list.bgiframe();
  612. }
  613. return {
  614. display: function(d, q) {
  615. init();
  616. data = d;
  617. term = q;
  618. fillList();
  619. },
  620. next: function() {
  621. moveSelect(1);
  622. },
  623. prev: function() {
  624. moveSelect(-1);
  625. },
  626. pageUp: function() {
  627. if (active != 0 && active - 8 < 0) {
  628. moveSelect( -active );
  629. } else {
  630. moveSelect(-8);
  631. }
  632. },
  633. pageDown: function() {
  634. if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
  635. moveSelect( listItems.size() - 1 - active );
  636. } else {
  637. moveSelect(8);
  638. }
  639. },
  640. hide: function() {
  641. element && element.hide();
  642. listItems && listItems.removeClass(CLASSES.ACTIVE);
  643. active = -1;
  644. },
  645. visible : function() {
  646. return element && element.is(":visible");
  647. },
  648. current: function() {
  649. return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
  650. },
  651. show: function() {
  652. var offset = $(input).offset();
  653. element.css({
  654. width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
  655. top: offset.top + input.offsetHeight,
  656. left: offset.left
  657. }).show();
  658. if(options.scroll) {
  659. list.scrollTop(0);
  660. list.css({
  661. maxHeight: options.scrollHeight,
  662. overflow: 'auto'
  663. });
  664. if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
  665. var listHeight = 0;
  666. listItems.each(function() {
  667. listHeight += this.offsetHeight;
  668. });
  669. var scrollbarsVisible = listHeight > options.scrollHeight;
  670. list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
  671. if (!scrollbarsVisible) {
  672. // IE doesn't recalculate width when scrollbar disappears
  673. listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
  674. }
  675. }
  676. }
  677. },
  678. selected: function() {
  679. var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
  680. return selected && selected.length && $.data(selected[0], "ac_data");
  681. },
  682. emptyList: function (){
  683. list && list.empty();
  684. },
  685. unbind: function() {
  686. element && element.remove();
  687. }
  688. };
  689. };
  690. $.fn.selection = function(start, end) {
  691. if (start !== undefined) {
  692. return this.each(function() {
  693. if( this.createTextRange ){
  694. var selRange = this.createTextRange();
  695. if (end === undefined || start == end) {
  696. selRange.move("character", start);
  697. selRange.select();
  698. } else {
  699. selRange.collapse(true);
  700. selRange.moveStart("character", start);
  701. selRange.moveEnd("character", end);
  702. selRange.select();
  703. }
  704. } else if( this.setSelectionRange ){
  705. this.setSelectionRange(start, end);
  706. } else if( this.selectionStart ){
  707. this.selectionStart = start;
  708. this.selectionEnd = end;
  709. }
  710. });
  711. }
  712. var field = this[0];
  713. if ( field.createTextRange ) {
  714. var range = document.selection.createRange(),
  715. orig = field.value,
  716. teststring = "<->",
  717. textLength = range.text.length;
  718. range.text = teststring;
  719. var caretAt = field.value.indexOf(teststring);
  720. field.value = orig;
  721. this.selection(caretAt, caretAt + textLength);
  722. return {
  723. start: caretAt,
  724. end: caretAt + textLength
  725. }
  726. } else if( field.selectionStart !== undefined ){
  727. return {
  728. start: field.selectionStart,
  729. end: field.selectionEnd
  730. }
  731. }
  732. };
  733. })(jQuery);