GrizzlyMcGee
GrizzlyMcGee

Reputation: 17

How can I detect highlighted text from a textarea?

I want to detect if text is highlighted in a textarea only, not the whole document. window.getSelection() works, but I don't want to grab text from any other part of the document that could be highlighted, just what's in the text area.

Basically, I'm trying to do this:

if (document.getElementById("mytextarea").getSelection) {
    //do stuff
}

What would be the easiest way to accomplish this? Thanks!

Upvotes: -1

Views: 430

Answers (2)

user6057915
user6057915

Reputation:

this should work (assuming by highlighted you mean selected)

var textarea = document.getElementById("tarea");  
var selection = (textarea.value).substring(textarea.selectionStart,textarea.selectionEnd);

console.log(selection); 
<textarea id="tarea"></textarea>

Upvotes: 2

Aldin
Aldin

Reputation: 70

I am posting the answer, regarding to this source: Get the Highlighted/Selected text - for detailed answer, please check that thread.

In general:

  function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    return text;
}

For <textarea>:

function getSelectionText() {
    var text = "";
    var activeEl = document.activeElement;
    var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;
    if (
      (activeElTagName == "textarea") || (activeElTagName == "input" &&
      /^(?:text|search|password|tel|url)$/i.test(activeEl.type)) &&
      (typeof activeEl.selectionStart == "number")
    ) {
        text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);
    } else if (window.getSelection) {
        text = window.getSelection().toString();
    }
    return text;
}

document.onmouseup = document.onkeyup = document.onselectionchange = function() {
  document.getElementById("sel").value = getSelectionText();
};
Selection:
<br>
<textarea id="sel" rows="3" cols="50"></textarea>
<p>Please select some text.</p>
<input value="Some text in a text input">
<br>
<input type="search" value="Some text in a search input">
<br>
<input type="tel" value="4872349749823">
<br>
<textarea>Some text in a textarea</textarea>

Upvotes: 1

Related Questions