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

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Norman In
  • 171
  • 1
  • 4
  • 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](https://www.w3.org/Bugs/Public/show_bug.cgi?id=24796) (it is specifically for number inputs; I haven't searched for a email type input discussion). Similar to http://stackoverflow.com/questions/21177489/selectionstart-selectionend-on-input-type-number-no-longer-allowed-in-chrome – Mottie Oct 30 '14 at 16:56

1 Answers1

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);
});
ankitkanojia
  • 3,072
  • 4
  • 22
  • 35
vidgarga
  • 320
  • 1
  • 3
  • 8
  • This solution works great. I'd set the timeout value to `1` though - `100` is slow enough to be noticeable. – Sauce Nov 18 '22 at 18:19