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,438
  • 68
  • 55
  • 126
Justin Meltzer
  • 12,978
  • 32
  • 114
  • 178

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
  • 36,569
  • 8
  • 80
  • 129