This question already has an answer here:
I'm trying to make my own WYSIWYG editor. Is there any way, how to get the text which has user selected in textarea?
For example, if user selects some word and then clicks button, how do I find out which text was selected?
I'm using jQuery.
Handling selection is different for different browsers:
That gives you a range object. Each range represents a single selection (using control/command key it's possible to make multiple active selections).
The type of range object you have now depends on what browser. For IE it's a Text Range object; for others its a Selection object. To convert a Selection object into a text range, you can call getRangeAt; for Safari, you need to build that:
The range object provides you with the starting and ending dom elements and text offset of the selection.
More information about range objects can be found at quirksmode.org here
If you are using jQuery, you may want to look at the light weight jQuery RTE Plugin by Batiste Bieler. It may do enough for your needs or at least give you something to start with.
For obtaining the selected content in a
<textarea>
with Firefox:window.getSelection().toString()
worked for me with Chrome but not Firefox.Reference:
getSelection()
This varies a bit by browser, see here for a function that alleges to work in most: http://snipplr.com/view/775/getselection/
A small function that will get the selected string/text of a textarea or input element :
Note that the above code needs jQuery for working. An example of getting the selected string of a input element with id abc123
The above function will return the selected string. If there is no string that is selected by the user, it will return
null
.More Examples
On elements selected with class name, selected string of the first element of the array of elements is returned and not the selected string of all the elements. After all, selection in a page will always be 1.
Try the jquery-fieldselection plugin.
You can download it from here. There is an example too.