Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 669
Justin Meltzer Avatar asked Oct 27 '25 09:10

Justin Meltzer


1 Answers

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);
like image 137
John Koerner Avatar answered Oct 28 '25 21:10

John Koerner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!