17

I'm trying to set my cursor to the position of the beginning when I'm on focus of a text box. This is what I have:

$("ID").focus(function () {
    var input = this;
    setTimeout(function() {
        input.setSelectionRange(0, 0);
    }, 0);
});

But I get this error every time I try to load the script:

Uncaught InvalidStateError: Failed to execute 'setSelectionRange' on 'HTMLInputElement': The input element's type ('email') does not support selection.

Guess I can't use setSelectionRange on emails. So, any other solutions on how to set my cursor position in the input text box (without changing the type email)?

1
  • 1
    There is no way around it if you want to keep the type="email". The type="number" has the same issue... you could voice your opinion in the discussion on w3.org (it is specifically for number inputs; I haven't searched for a email type input discussion). Similar to stackoverflow.com/questions/21177489/…
    – Mottie
    Oct 30, 2014 at 16:56

1 Answer 1

5

It is true, it seems that there is a bug when using the setSelectionRange function for email input. So what can be done is to modify the type of the input so that setSelectionRange works and not an error.

$('#ID').focus(function () {
    var input = this;
    setTimeout(function () {
        $(input).attr('type', 'text');
        input.setSelectionRange(0, 0);
        $(input).attr('type', 'email');
    }, 100);
});
1
  • This solution works great. I'd set the timeout value to 1 though - 100 is slow enough to be noticeable.
    – Sauce
    Nov 18, 2022 at 18:19

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.