admin管理员组

文章数量:1314832

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

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

Share Improve this question edited Nov 21, 2022 at 8:32 sideshowbarker 88.4k29 gold badges215 silver badges212 bronze badges asked Oct 30, 2014 at 16:34 Norman InNorman In 1911 silver badge4 bronze badges 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 (it is specifically for number inputs; I haven't searched for a email type input discussion). Similar to stackoverflow./questions/21177489/… – Mottie Commented Oct 30, 2014 at 16:56
Add a ment  | 

1 Answer 1

Reset to default 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);
});

本文标签: javascriptType Email doesn39t support selectionrangeStack Overflow