Javascript get selected text from any textinput/textarea on the page

Baruch picture Baruch · Jun 20, 2011 · Viewed 17.4k times · Source

How can get the selected text from a textbox/textarea if I don't know which one active (focused). I am trying to create a small bookmarklet that will correct the selected text in any type of input on a page.

Answer

pimvdb picture pimvdb · Jun 20, 2011

For the selection, you want selectionStart and selectionEnd.

As for the currently focused element, use document.activeElement.

So as a combination you can use: http://jsfiddle.net/rBPte/1/.

As Tim Down pointed out, you'd need a more complex solution for Internet Explorer version 8 or lower: Caret position in textarea, in characters from the start

function getText(elem) { // only allow input[type=text]/textarea
    if(elem.tagName === "TEXTAREA" ||
       (elem.tagName === "INPUT" && elem.type === "text")) {
        return elem.value.substring(elem.selectionStart,
                                    elem.selectionEnd);
        // or return the return value of Tim Down's selection code here
    }
    return null;
}

setInterval(function() {
    var txt = getText(document.activeElement);
    document.getElementById('div').innerHTML =
        txt === null ? 'no input selected' : txt;
}, 100);