How to get selected text from textbox control with javascript

OK, here is the code I have:

function ShowSelection()
{
  var textComponent = document.getElementById('Editor');
  var selectedText;

  if (textComponent.selectionStart !== undefined)
  {// Standards Compliant Version
    var startPos = textComponent.selectionStart;
    var endPos = textComponent.selectionEnd;
    selectedText = textComponent.value.substring(startPos, endPos);
  }
  else if (document.selection !== undefined)
  {// IE Version
    textComponent.focus();
    var sel = document.selection.createRange();
    selectedText = sel.text;
  }

  alert("You selected: " + selectedText);
}

Problem, although the code I give for IE is given on lot of sites, I cannot make it work on my copy of IE6 on my current system. Perhaps it will work for you, that's why I give it.
The trick you look for is probably the .focus() call, to give back to textarea the focus so the selection is re-activated.

[UPDATE] I got the right result (the selection content) with onKeyDown event:

document.onkeydown = function (e) { ShowSelection(); }

So the code is correct. Again, the issue is to get the selection on click on a button... I continue to search.

[UPDATE] I got no success with a button drawn with a li tag, because when we click on it, IE deselects the previous selection. The above code works with a simple input button, though...


Here's a much simpler solution, based on the fact that text selection occurs on mouseup, so we add an event listener for that:

document.querySelector('textarea').addEventListener('mouseup', function () {
  window.mySelection = this.value.substring(this.selectionStart, this.selectionEnd)
  // window.getSelection().toString();
});
<textarea>
  Select some text
</textarea>
<a href="#" onclick=alert(mySelection);>Click here to display the selected text</a>

This works in all browsers.

If you also want to handle selection via the keyboard, add another event listener for keyup, with the same code.

If it weren't for this Firefox bug filed back in 2001 (yes, 14 years ago), we could replace the value assigned to window.mySelection with window.getSelection().toString(), which works in IE9+ and all modern browsers, and also gets the selection made in non-textarea parts of the DOM.


function disp() {
  var text = document.getElementById("text");
  var t = text.value.substr(text.selectionStart, text.selectionEnd - text.selectionStart);
  alert(t);
}
<TEXTAREA id="text">Hello, How are You?</TEXTAREA><BR>
<INPUT type="button" onclick="disp()" value="Select text and click here" />