15

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.

Baruch
  • 20,590
  • 28
  • 126
  • 201
  • I'm sorry, but can you clarify the question for me: Do you want the content of the currently focused textarea/input field or the content of a specific field regardless of the current focus? – nfechner Jun 20 '11 at 19:00
  • I think this is about the *selected*, or highlighted, part of a text element or textarea value. – Pointy Jun 20 '11 at 19:01
  • When do you want to get the selected text? For example, if it's on a button click or something similar, then none of the inputs or textareas will be focused. – FishBasketGordo Jun 20 '11 at 19:20
  • @FishBasketGordo This is for a bookmarklet. I will click it outside the document window - on the shortcuts toolbar. – Baruch Jun 21 '11 at 16:50

1 Answers1

33

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);
Community
  • 1
  • 1
pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • 1
    You might want to add a bit of defensive code here, this will throw errors when you select actual elements (try highlighting the textboxes themselves and watch your console output) – josh.trow Jun 20 '11 at 19:13
  • 2
    `selectionStart` and `selectionEnd` are not supported on IE < 9. See my answer here for a cross-browser function to work round this: http://stackoverflow.com/questions/263743/how-to-get-cursor-position-in-textarea/3373056#3373056 – Tim Down Jun 20 '11 at 21:25
  • Good. How can we do with out using setInterval, using event? – Henok Tesfaye Jun 27 '19 at 12:54