0

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.

Acorn
  • 49,061
  • 27
  • 133
  • 172

5 Answers5

3

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.

Neil
  • 54,642
  • 8
  • 60
  • 72
  • Thanks for the `setSelectionRange` tip – Acorn Aug 07 '11 at 20:30
  • 1
    To be more specific about the browsers, `selectionStart` and `selectionEnd` are fine in everything major except IE < 9. Also, `selectionStart` and `selectionEnd` are writable, so you can either use them or `setSelectionRange()`. I'm not sure why the redundancy is there. – Tim Down Aug 07 '11 at 22:05
2

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.

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

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;">
Eric Fortis
  • 16,372
  • 6
  • 41
  • 62
1

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

rlemon
  • 17,518
  • 14
  • 92
  • 123
0

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

dcastro
  • 66,540
  • 21
  • 145
  • 155