Get caret position and selection range of any input type without using selectionStart and selectionEnd

13 Views Asked by At

According to the WHATWG forms spec selectionStart property applies only to inputs of types text, search, URL, tel, and password. This useful solution to get the caret position and the selection range does not work with input elements with type email, number, month, number and week, despite all of these looking somewhat like normal text inputs.

I need to know the position of the caret so, when an user types in an input, I can get the exact character and position where the character was inserted, so I insert the same character in an equivalent position in another input. In the application I'm building, this is trivial to do once I have the position where the character was inserted. The selection range is a bonus for a future feature I have in mind, but no big deal if I can't get it now, I guess.

Simply copying and pasting the entire input value is an option if nothing else works, but I want to know what are my options.

How to get the same behavior of selectionStart (and selectionEnd) with these input types?

I've tried using document.getSelection().getRangeAt(0) and approaches that base itself in the Selection object, but they have failed. As I've come to understand, apparently it does not detect selection of text inside inputs, only across nodes?

A common solution to support IE involves something like document.selection, but selection doesn't seem to even exist in the document object nowadays.

0

There are 0 best solutions below