TextArea SelectedText, SelectionStart, SelectionEnd, SelStart, SelEnd (IE and FireFox)
Simple way of getting the html textarea’s selection properties selectedText, selectionStart, selectionEnd:
Javascript:
function getTextAreaSelection() {
var textArea = document.getElementById('textarea1');
if (document.selection) { //IE
var bm = document.selection.createRange().getBookmark();
var sel = textArea.createTextRange();
sel.moveToBookmark(bm);
var sleft = textArea.createTextRange();
sleft.collapse(true);
sleft.setEndPoint("EndToStart", sel);
textArea.selectionStart = sleft.text.length
textArea.selectionEnd = sleft.text.length + sel.text.length;
textArea.selectedText = sel.text;
}
else if (textArea.selectionStart){ //FF
textArea.selectedText = textArea.substring(textArea.selectionStart,textArea.selectionEnd);
}
alert("Selection Start==> " + textArea.selectionStart + "\n" +
"Selection End ==> " + textArea.selectionEnd + "\n" +
"Selected Text ==> " + textArea.selectedText + "\n" +
"TextArea Value ==> " + textArea.value);
}
HTML:
<textarea id="textarea1"></textarea> <button onclick="getTextAreaSelection()">Get Selection Info</button>
Jim 7:50 am on September 6, 2009 Permalink |
What if the selected text is repeated within the content?
“textArea.value.indexOf” will return the first instance of the selected text, but that may not be the text that is actually selected, they are just the same because they are repeated.
For example: “My name is Fred, and his name is John.”
If I select the second instance of “name is”, when I run your function I will get the first. This isn’t a problem if you just want to know the text that is selected, but it is if you want to manipulate it.
jmaglasang 1:59 pm on September 10, 2009 Permalink |
You have a point there them, I have update the code but there is still a little problem, it cannot return the correct caret position in IE.