Type Email doesn't support selectionrange
Asked Answered
A

1

19

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

Amelita answered 30/10, 2014 at 16:34 Comment(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 #21177989Spinster
T
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);
});
Terence answered 29/11, 2019 at 13:55 Comment(1)
This solution works great. I'd set the timeout value to 1 though - 100 is slow enough to be noticeable.Foliation

© 2022 - 2024 — McMap. All rights reserved.