PageRenderTime 134ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/public/js/lib/jquery.autocomplete_geomod.js

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