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 2,892 times
4
Brian Tompsett - 汤莱恩
- 5,438
- 68
- 55
- 126
Justin Meltzer
- 12,978
- 32
- 114
- 178
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
- 36,569
- 8
- 80
- 129
-
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