How to get selected text from a 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)
  { // Internet Explorer version
    textComponent.focus();
    var sel = document.selection.createRange();
    selectedText = sel.text;
  }

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

The problem is, although the code I give for Internet Explorer is given on a lot of sites, I cannot make it work on my copy of Internet Explorer 6 on my current system. Perhaps it will work for you, and that’s why I give it.

The trick you look for is probably the .focus() call to give the focus back to the textarea, so the selection is reactivated.

I got the right result (the selection content) with the 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.

I didn’t have any success with a button drawn with a li tag, because when we click on it, Internet Explorer deselects the previous selection. The above code works with a simple input button, though…

Leave a Comment