How can I get the selected text in a textarea? [duplicate]

window.getSelection().toString() worked for me with Chrome, but not Firefox.

For obtaining the selected content in a <textarea> with Firefox:

function getSel() // JavaScript
{
    // Obtain the object reference for the <textarea>
    var txtarea = document.getElementById("mytextarea");

    // Obtain the index of the first selected character
    var start = txtarea.selectionStart;

    // Obtain the index of the last selected character
    var finish = txtarea.selectionEnd;

    // Obtain the selected text
    var sel = txtarea.value.substring(start, finish);


    // Do something with the selected content
}

You could also use activeElement instead of getElementById.

Reference:

Leave a Comment