4

I am trying to find the textual start and end of the selection. So, in the following text, if I selected "world! What a fine" from within "Hello, world! What a fine day it is!", I should get 7 as the start coordinate, and 24 as the end coordinate assuming a zero based index.

How is this achievable?

EDIT: I am looking to find the selection of text that is not inside any <input> or <textarea> elements.

EDIT: Decided the solution to use disabled <textarea>s

Tyler
  • 19,113
  • 19
  • 94
  • 151

3 Answers3

2

I use this:

/* Returns 3 strings, the part before the selection, the part after the selection and the selected part */
function getSelected()
{
  var u     = editor.val();
  var start = editor.get(0).selectionStart;
  var end   = editor.get(0).selectionEnd;

  return [u.substring(0, start), u.substring(end), u.substring(start, end)];
}

where editor is $("#editor") or whatever ID your textarea / input field may have.

Usage:

var select = getSelected()
editor.val(select[0] + '<h1>'+ select[2] + '</h1>' + select[1]);

Will wrap selected text in H1. If nothing is selected it will just add empty H1, but you can add checks and functionality to your liking.

** Not tested in all browsers, works in Chrome though **

Tessmore
  • 1,054
  • 1
  • 9
  • 23
  • Did you see my edit that I want this to work in DIVs and Ps? I edited it like 5 minutes before your answer so you might not have seen it. This works fine in TEXTAREA, but start and end are `undefined` when applied to a P tag. – Tyler Dec 18 '11 at 05:01
  • It seems as if this would be the correct solution if I were to switch from using
    s to disabled
    – Tyler Dec 19 '11 at 05:10
  • ah glad I could still help out :) – Tessmore Dec 19 '11 at 11:50
  • This does not work in IE below version 9, because `selectionStart` and `selectionEnd` are not supported: http://help.dottoro.com/ljtfkhio.php – kasimir Sep 04 '13 at 09:36
2

This is possible but slightly complicated with contenteditable HTML content (as opposed to text within an <input> or <textarea> element). Here's a simple cross-browser implementation:

https://stackoverflow.com/a/4812022/96100

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
0

But I know a jQuery plugin that aims your problem and much more - https://github.com/localhost/jquery-fieldselection

Bakudan
  • 19,134
  • 9
  • 53
  • 73