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.
Asked
Active
Viewed 3,256 times
4

Brian Tompsett - 汤莱恩
- 5,753
- 72
- 57
- 129

Justin Meltzer
- 13,318
- 32
- 117
- 182
1 Answers
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
-
Thanks! What's browser support for this? – Justin Meltzer Jan 30 '13 at 04:24
-
It will work in modern browsers. For older IE, you will need to do something like this: http://stackoverflow.com/q/263743/573218 – John Koerner Jan 30 '13 at 04:26