Reputation: 50497
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
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
Reputation: 68660
The ::selection selector might work as well. http://www.w3schools.com/cssref/sel_selection.asp
Upvotes: 0
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
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