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)?
<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.
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.
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.
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> .
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With