omg
omg

Reputation: 139832

how to get selected text inside a textarea element by javascript?

I'm not familiar with such attributes,

can someone provide a simple demo?

I need it to be done without any libraries.

Upvotes: 3

Views: 13475

Answers (1)

user2851996
user2851996

Reputation: 77

<script type="text/javascript">

        function ShowSelectionInsideTextarea()
{
 var textComponent = document.getElementById('mytextarea');

  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);

}
</script>

Upvotes: 6

Related Questions