0

We have a few text areas that have some text the user may copy to their clipboard.

Without going into too much detail as it will just complicate a straightforward question:

Is it possible to detect if a textarea's contents are 'selected'?


I should mention using the onclick (or other) event handlers are (ideally...) not an option.

As this text is selected by an 'outside of the textarea' action.

The flow is somewhat as follows:

Drop down choice is chosen -> Text in textarea is selected

Or

Textarea is clicked (onclick) -> Text in textarea is selected

I know we could use a whole bunch of event handlers to detect the state of the text in the textarea, but I was hoping there was a simpler way of doing by detecting the state of the text inside the textarea via JavaScript.

1

3 Answers 3

3

The selectionStart and selectionEnd properties hold the selection indexes.

var textarea = document.getElementById("textarea1");
if(textarea.selectionStart == textarea.selectionEnd) alert("Nothing is selected!")
Sign up to request clarification or add additional context in comments.

Comments

2

This code is taken from this question. You'll need to adapt the code slightly, but it shows how to access the selection for both Mozilla and Internet Explorer browsers -

function ShowSelection()
{
  var textComponent = document.getElementById('Editor');
  var selectedText;
  // Internet Explorer version
  if (document.selection != undefined)
  {
    textComponent.focus();
    var sel = document.selection.createRange();
    selectedText = sel.text;
  }
  // Mozilla version
  else if (textComponent.selectionStart != undefined)
  {
    var startPos = textComponent.selectionStart;
    var endPos = textComponent.selectionEnd;
    selectedText = textComponent.value.substring(startPos, endPos)
  }
  alert("You selected: " + selectedText);
}

1 Comment

selected this answer because of the trident vs proper browser fork. thank you!
1

Have a look at this demo. They use the jQuery - fieldSelection plugin.

1 Comment

both are valid answers, but we dont use jquery :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.