'Get index of selected text inside text input

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.



Solution 1:[1]

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);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 John Koerner