Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 641
Baruch Avatar asked Jun 20 '11 18:06

Baruch


People also ask

How to get selected text from textarea in js?

Note that the above code needs jQuery for working. An example of getting the selected string of an input element with id abc123 is: getInputSelection($("#abc123")); The above function will return the selected string.

How do you select text in HTML?

HTML | DOM Input Text select() Method The DOM Input select() method selects all the text content of a textarea or an input element which contains the text field. Syntax: element. select();


1 Answers

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);
like image 120
pimvdb Avatar answered Sep 20 '22 04:09

pimvdb