Maintain cursor position after changing an input value programatically

Sometimes you want to programatically change an input value, like in a case of input validation.
replacing an input value is easy, but has a common drawback – the cursor position will reset.

to overcome it, we can use this simple JS snippet:

function handleInputValueChange(e) {

    var cursorStart =,
        cursorEnd =;

        // value manipulations..., cursorEnd);

* note that this specific snippet relies on passing an event, onChange for instance.

Leave a Reply

Your email address will not be published. Required fields are marked *