Textareas and text inputs have a different selection API from the main document selection. Use selectionStart
and selectionEnd
properties of the textarea/input.
function myFunction(obj) {
var selectedText = obj.value.slice(obj.selectionStart, obj.selectionEnd);
alert(selectedText);
}
If you need support for IE <= 8, there is a different API again. See Caret position in textarea, in characters from the start