4

If you have an HTML input element, how can you detect the index of starting and ending positions of selected text inside that input? I tried using window.getSelection but it does not seem to work correctly. I would need to figure this out on the keydown event.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Justin Meltzer
  • 13,318
  • 32
  • 117
  • 182

1 Answers1

3

You can use the selectionStart and selectionEnd property to get the indexes of the respective values.

var start = document.getElementById("myArea").selectionStart;  
var end = document.getElementById("myArea").selectionEnd;

console.log(start);
console.log(end);
John Koerner
  • 37,428
  • 8
  • 84
  • 134