Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type Email doesn't support selectionrange

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

like image 872
Norman In Avatar asked Oct 30 '14 16:10

Norman In


People also ask

What is type email?

<input> elements of type email are used to let the user enter and edit an e-mail address, or, if the multiple attribute is specified, a list of e-mail addresses.

What is the input type for email in HTML?

The <input type="email"> defines a field for an e-mail address. The input value is automatically validated to ensure it is a properly formatted e-mail address. To define an e-mail field that allows multiple e-mail addresses, add the "multiple" attribute.

What does setSelectionRange do?

setSelectionRange() method sets the start and end positions of the current text selection in an <input> or <textarea> element. Optionally, in newer browser versions, you can specify the direction in which selection should be considered to have occurred.

What is selectionEnd?

Similarly, selectionEnd specifies the index where the selection ends. Initially, they are set to 0 , and if the <textarea> is focused but no text is selected, the selectionStart and selectionEnd values will be the same, and reflect the position of the caret within the value of the <textarea> .


1 Answers

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);
});
like image 137
vidgarga Avatar answered Sep 17 '22 17:09

vidgarga