Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 628
omg Avatar asked May 23 '26 23:05

omg


1 Answers

<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>
like image 80
user2851996 Avatar answered May 25 '26 11:05

user2851996