Programmatically Selecting Text in an Input Field on iOS Devices (Mobile Safari)

Programmatically selecting text in an input field on iOS devices (mobile Safari)

input.setSelectionRange(0, 9999);

https://developer.mozilla.org/en/DOM/Input.select

Mobile Safari jQuery select() on focus input doesn´t work

I changed the javascript to this (changed how selection of text is done and how to get input variable):

        $(document).ready(function() {
//Select text on focus for input
$("input:text").focus(focustext);
});
function focustext() {
var input = this;
setTimeout(function () {
input.selectionStart = 0;
input.selectionEnd = input.val().length;
},100);
}

and now it works as intented. inputs with type=number does not seem to work though.

I have tested this on iOS6 and iOS7, and it also works in latest Chrome and IE on Windows 7. IE in compability mode does not work, though.

Mobile Safari Autofocus text field

I think this is a feature of mobile Safari rather than a bug. In our work on FastClick, my colleagues and I found that iOS will only allow focus to be triggered on other elements, from within a function, if the first function in the call stack was triggered by a non-programmatic event. In your case, the call to setTimeout starts a new call stack, and the security mechanism kicks in to prevent you from setting focus on the input.

Remember that on iOS setting focus on an input element brings up the keyboard - so all those web pages out there that set focus on an input element on page load, like Google does, would be extremely annoying to use on iOS. I guess Apple decided they had to do something to prevent this. So I disagree with @DA: this is a feature not a bug.

There's no known workaround for this, so you'll have to ditch the idea of using a delay.

Update August 2012:

As of iOS 5, handlers triggered by synthesised click events are allowed to trigger focus on input elements. Try the updated FastClick input focus example.



Related Topics



Leave a reply



Submit