Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

Something as simple as the jQuery .select() should just work across all browsers and platforms but it doesn't. I know jQuery Mobile attempts to solve the deficiencies that the multi-platform/device ecosystem creates, however not everyone wants to use jQM and sometimes it's easier to create a small workaround. This is exactly what I did to get input field text selection working for my Travel Microblog project.

This is what I was trying to achieve...A popover div displaying an <input type="text"> form element with a URL. I wanted to have this field focused and its text selected as soon as it was displayed.
iosinpselect.jpg


My first version of the code went something like this...
 This doesn't work on iOS
var shareInput = $.('input#shareUrl');
shareInput.focus();
shareInput.select();


That worked on all the browsers I tried it with on the desktop, but refused to select the text on my iPhone. Apparently this is a known issue, the solution relies on not using .select()! Counterintuitive isn't it!

So if .select() can't be used what then?



The trick is to go back to the non-jQuery code (I know right!) and set the selection manually. For this you set the selectionStart and selectionEnd attributes.

The code now becomes something like this...
 This works on iOS
var shareInput = $.('input#shareUrl');
shareInput.focus();
shareInput[0].selectionStart = 0;
shareInput[0].selectionEnd = shareInput.val().length;


Bit ugly, but it works.

-i

A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. Use of any information from my blog posts should be at own risk and I do not hold any liability towards any information misuse or damages caused by following any of my posts.

All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle). Use of any information contained in this blog post/article is subject to this disclaimer.
Hi! You can search my blog here ⤵
NOTE: (2022) This Blog is no longer maintained and I will not be answering any emails or comments.

I am now focusing on Atari Gamer.