Acorn
Acorn

Reputation: 50497

Get currently selected text on page

How would you get the currently selected text within a textarea (and modify it)?

I've seen the select event that can be listened for, but I was wondering if there was a way to just get the currently selected text.

Also, what technique do you need to use in order to be able to modify that specific section of text within the textarea? I assume there's some way of finding out what the position of the selection is within the contents of the textarea as a whole?

What I want to be able to do is take the selection and modify it, or wrap it in certain tags etc., like you are able to do in the stackexchange text editor.

Upvotes: 0

Views: 1658

Answers (5)

Tim Down
Tim Down

Reputation: 324547

I've posted what I consider the definitive function to do this in all browsers (including IE < 9) on Stack Overflow many times. Here's one example:

IE's document.selection.createRange doesn't include leading or trailing blank lines

I'd also recommend my jQuery plug-in for this, which includes this function and others to insert, delete, surround or replace the selected text, which sounds like exactly what you want. It's also the only jQuery plug-in for textarea selections I'm aware of that works correctly with line breaks in IE < 9.

Upvotes: 2

dcastro
dcastro

Reputation: 68660

The ::selection selector might work as well. http://www.w3schools.com/cssref/sel_selection.asp

Upvotes: 0

Neil
Neil

Reputation: 55392

If you only have to support the latest browsers, you can use the selectionStart and selectionEnd properties which expose the character positions of the text selected in the textarea. You can't modify just the selected text but having updated the value you can use setSelectionRange to reselect the text.

Upvotes: 3

rlemon
rlemon

Reputation: 17666

jquery field selection plugin.. Download Here examples on site.

Upvotes: 1

Eric Fortis
Eric Fortis

Reputation: 17350

From this page

http://www.netadmintools.com/art466.html

function display(txtarea) {
  var sl = (txtarea.value)
     .substring(txtarea.selectionStart, txtarea.selectionEnd);        
} 


<body onload="thisForm=document.frmKey;">

Upvotes: 1

Related Questions