code

text selection

little demo for getting and setting text selectionz.

html

<p>
  <input type="text" id="mytextbox" size="20" value="foo bar" />
</p>
<p>
  <button onclick="_setSelection()">set selection</button>
  <button onclick="_getSelection()">get selection</button>
</p>
<p id="selection"></p>

javascript

//https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange

function _setSelection() {
  var input = document.getElementById("mytextbox");
  input.focus();
  input.setSelectionRange(2, 5);
}

function _getSelection() {
  var s = window.getSelection();
  var elem = document.getElementById("selection");
  elem.innerHTML = "selected: " + s;
}

this demo preserves the compiled output and may depend on external libraries or services that are no longer available.

original jsfiddle post