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 straight forward question:

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


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

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

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 was hoping there was a simpler way of doing by detecting the state of the text inside the textarea via js.


Thanks

anonymous-one
  • 12,434
  • 18
  • 52
  • 80
  • See http://stackoverflow.com/questions/401593/javascript-textarea-selection/403526#403526 and http://stackoverflow.com/questions/717224/how-to-get-selected-text-in-textarea – Sahil Muthoo Sep 13 '11 at 08:31

3 Answers3

4

The selectionStart and selectionEnd properties hold the selection indexes.

var textarea = document.getElementById("textarea1");
if(textarea.selectionStart == textarea.selectionEnd) alert("Nothing is selected!")
Rob W
  • 315,396
  • 71
  • 752
  • 644
1

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

Reto Aebersold
  • 15,409
  • 4
  • 49
  • 69
1

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 IE browsers -

function ShowSelection()
{
  var textComponent = document.getElementById('Editor');
  var selectedText;
  // IE 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);
}
Community
  • 1
  • 1
ipr101
  • 23,344
  • 6
  • 55
  • 60