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

Viewed 75572

How do you programmatically select the text of an input field on iOS devices, e.g. iPhone, iPad running mobile Safari?

Normally it is sufficient to call the .select() function on the <input ... /> element, but this does not work on those devices. The cursor is simply left at the end of the existing entry with no selection made.

10 Answers

Something like the following is working for me for me on Webkit that comes with Android 2.2:

function trySelect(el) {
    setTimeout(function() {
        try {
            el.select();
        } catch (e) {
        }
    }, 0);
}

See Chromium Issue 32865.

I went nuts looking for this solution, while all your responses did help it opened another can of worms for me.

The client wanted the user to be able to click and select all, and also let the user 'tab' and select all on the iPad (with an external keyboard. I know, crazy...)

My solution to this problem was, rearrange the events. First Focus, then Click, then touchstart.

$('#myFUBARid').on('focus click touchstart', function(e){
  $(this).get(0).setSelectionRange(0,9999);
  //$(this).css("color", "blue");
  e.preventDefault();
});

I hope this helps someone, as you lot have helped me countless times.

Related