I have the following jQuery code (similar to this question) that works in Firefox and IE, but fails (no errors, just doesn\'t work) in Chrome and Safari. Any ideas for a wo
Use setSelectionRange()
inside of a callback to requestAnimationFrame()
:
$(document).on('focus', '._selectTextOnFocus', (e) => {
var input = e.currentTarget;
var initialType = e.currentTarget.type;
requestAnimationFrame(() => {
// input.select() is not supported on iOS
// If setSelectionRange is use on a number input in Chrome it throws an exception,
// so here we switch to type text first.
input.type = "text";
input.setSelectionRange(0, Number.MAX_SAFE_INTEGER || 9999);
input.type = initialType;
});
});
Use setSelectionRange()
instead of select()
since select()
doesn't work in mobile Safari (see Programmatically selecting text in an input field on iOS devices (mobile Safari)).
It is necessary to wait using requestAnimationFrame
before selecting the text, otherwise the element isn't correctly scrolled into view after the keyboard comes up on iOS.
When using setSelectionRange()
it is important to set the input type to text
, otherwise it may throw exceptions on Chrome (see selectionStart/selectionEnd on input type="number" no longer allowed in Chrome).