/src/main/webapp/public/js/lib/jquery.autocomplete.js

http://thoughtsite.googlecode.com/ · JavaScript · 806 lines · 661 code · 74 blank · 71 comment · 172 complexity · 5a279fefddc94d35defff490ebe04953 MD5 · raw file

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