89

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.

sroebuck
  • 6,060
  • 4
  • 25
  • 18
  • 10
    I don't see any reason why being a touch device changes the relevance of pre-selecting text. What you said about a touch device can equally well be said of a non-touch device. I want to pre-select text when a user chooses to touch an item to edit it. In most cases the user is likely to want to replace the existing contents in which case they would be able to do that without any further touching and dragging. In other cases when they want to edit the existing content they would be able to deselect or change the selection. – sroebuck Jul 19 '10 at 15:07
  • 2
    Unfortunately .focus().select() doesn't work. – sroebuck Jul 19 '10 at 15:08
  • 2
    I'm starting a bounty on this issue. My goal is to make it very easy for users to click on my textarea and tap "Copy" to copy the text to the clipboard. – Dan Fabulich Aug 29 '10 at 22:56
  • Same here.. there seem to be a lot of methodes not working in Mobile Safari .select() and .focus() are two of those. –  Oct 19 '10 at 19:36
  • @sroebuck nice answer for David W. Keith! thumbs up! – eyurdakul Aug 24 '15 at 13:32

10 Answers10

95
input.setSelectionRange(0, 9999);

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

Stalinko
  • 3,319
  • 28
  • 31
jobwat
  • 8,527
  • 4
  • 31
  • 30
  • 3
    This worked for me but had to include stopping the mouseup on the same inputs. – DuStorm May 25 '12 at 21:31
  • 9
    This did not work for me on either an iPad or an iPhone – Doug Feb 12 '14 at 16:01
  • 5
    This only worked for me if I triggered `.focus()` on the input before invoking `input.setSelectionRange`. If you're listening for the `focus` event on the input, remember to account for an infinite loop. – allieferr May 29 '14 at 19:37
  • 10
    A gotcha that is worth mentioning: this will not work on textareas if they have the `readonly` attribute set. – JayPea Jun 23 '14 at 18:15
  • It also won't work on iOS if the textarea is `disabled` – zok Aug 21 '14 at 18:01
  • @allieferr can you explain more about the infinite loop? – Atav32 Oct 15 '14 at 21:19
  • @JayPea what is your solution? – SuperSpy Jun 30 '15 at 18:20
  • 7
    I spent over an hour playing with various solutions. Calling `setSelectionRange()` in a `focus` handler works when you trigger `.focus()` programmatically, but when you manually tap into the text input on iOS, the selection does not happen. Suffice it to say, all you need to do is call `setSelectionRange()` within a setTimeout of 0 and it works as expected no matter what triggers the focus. –  Apr 01 '16 at 06:11
  • Note: this doesn't work if the input is of type="number". Failed to execute 'setSelectionRange' on 'HTMLInputElement': The input element's type ('number') does not support selection. – Peter Jan 20 '20 at 08:54
32

Nothing in this thread worked for me, here's what works on my iPad:

// t is the input field
setTimeout(function() {
    t.setSelectionRange(0, 9999);
}, 1);
nkrop
  • 321
  • 3
  • 3
26

See this fiddle: (enter some text in the input box and click 'select text')

It is selecting text in an inputbox on my iPod (5th gen iOS6.0.1), opening the keyboard and also showing the Cut/Copy/Suggest... menu

Using plain javascript. Did not try this with jQuery

document.getElementById("p1").selectionStart = 0
document.getElementById("p1").selectionEnd = 999

Note that the number 999 is just a sample. You should set these numbers to the number of characters you want to select.

UPDATE:

  • iPod5 - iOS6.0.1 - Working ok.
  • iPad1 - iOS5.1.1 - Only text selected. Tap selection once to open Cut/Copy menu
  • iPad2 - iOS4.3.3 - Only text selected. Tap selection once to open Cut/Copy menu

For the last two, you might experiment by triggering a click event on the input element

UPDATE: (07-10-2013)

  • iPod5 - iOS7.0.2 - Using the fiddle in the link: Can't see typed text in input box. Pressing select redirects me to facebook.com (??? wtf ???) no idea what's going on there.

UPDATE: (14-11-2013)

  • iOS 7.0.3 : Thanks to the comment from binki update that the .selectionStart and .selectionEnd does work.

UPDATE: (15-01-2015)

  • iOS 8.x.x : Thanks to the comment from Michael Siebert. Taken from the comment: I had to listen for both focus AND click events and then setTimeout/_.debounce to make it work in both cases: click the input or focus through tabbing
Community
  • 1
  • 1
bart s
  • 5,068
  • 1
  • 34
  • 55
  • You are my hero for today! Works like a charm! ;-) – andi1984 Dec 07 '12 at 12:39
  • 3
    @andi1984 where do I claim the hero badge? – bart s Dec 07 '12 at 12:44
  • 1
    Do you know about the compatibility to other iOS versions? Does it work on iOS5 and iOS4? – andi1984 Dec 07 '12 at 13:34
  • 1
    Works for me on iOS6 BUT a) doesn't work on desktop Chrome b) doesn't work when text input is disabled :( My use case: I generate unique URL and want faciliate sharing. – Mars Robertson Aug 11 '13 at 20:39
  • 1
    @barts I’m going to guess that you ended up on Facebook because the “Share” menu at jsfiddle must be messed up and tappable while invisible perhaps. I ended up clicking the invisible Twitter button myself when testing with iOS-7.0.3 on an iPad. I also found that when I thought I was tapping on your ``, the iPad thought I was tapping in jsfiddle’s “CSS” pane (wherein anything I typed was invisible). Once I got my tap directed at the correct ``, your “select text” button works perfectly fine on iOS-7.0.3 :-). – binki Nov 12 '13 at 18:27
  • @binki Actually, I wasn’t tapping in the “CSS” pane, I was tapping in the “embed this code” or similar text things in jsfiddle’s Share dropdown. – binki Nov 12 '13 at 18:34
  • @binki thanks for the comment... glad to know I am not the only one :-) – bart s Nov 13 '13 at 06:27
  • @barts Well, my point was, the `.selectionStart` plus `.selectionEnd` *does* work in iOS-7.0.3, care to update your post :-p? – binki Nov 14 '13 at 16:02
  • Update for IOS 8: I had to listen for both focus AND click events and then setTimeout/_.debounce to make it work in both cases: click the input or focus through tabbing. – Michael Siebert Jan 15 '15 at 11:43
  • @MichaelSiebert: could you add the specific iOS version please? I will update the post according to that. – bart s Jan 15 '15 at 14:09
  • To make it work for IOS 'document.getElementById("p1").setSelectionRange(0, 9999)' – Milad Dec 17 '17 at 08:15
  • Possible to update the fiddle with the iOS 8 working code? – carestad Mar 06 '18 at 18:55
  • @carestad: unfortunately I do not have iOS devices at hand anymore. I will not be able to update the fiddle and test it for correct operation. – bart s Mar 09 '18 at 10:18
26

It's hard to prove a negative, but my research suggests this is a bug in Mobile Safari.

Note that focus() works, more or less—though it can require more than one tap to succeed, and it's not necessary if you're trying to respond to a user tap on the field in question as the tap itself will give the field focus. Unfortunately, select() is simply non-functional in Mobile Safari.

Your best bet may be a bug report with Apple.

clozach
  • 5,118
  • 5
  • 41
  • 54
7

Sorry, in my earlier post, I didn't notice the Javascript implying that you wanted an answer in Javascript.

To get what you want in UIWebView with javascript, I have managed to scrape together two important pieces of info to get it to work. Not sure about the mobile browser.

  1. element.setSelectionRange(0,9999); does what we want

  2. mouseUp event is undoing the selection

Thus (using Prototype):

    input.observe('focus', function() {
      this.setSelectionRange(0, 9999);
    });
    input.observe('mouseup', function(event) {
      event.stop();
    });

does the trick.

Matt

Matt
  • 4,261
  • 4
  • 39
  • 60
  • 3
    We're having the same issue and found your solution worked - but we're using jquery (mobile actually). /* select the text inside the fill-ins */ $("input").focus(function () { this.setSelectionRange(0, 9999); return false; } ).mouseup( function () { return false; }); – DuStorm May 25 '12 at 21:28
  • 1
    I'm using iOS 8 on iPad and iPhone, and the code from @DuStorm (comment above this one) is the only thing that worked for me out of all the answers given here. To reiterate, the following at least works on iOS 8 in Chrome and Safari: `$("input").focus(function () { this.setSelectionRange(0, 9999); return false; } ).mouseup( function () { return false; });` – Aaron Jessen Nov 19 '14 at 18:15
  • I had to use `focusin` instead of focus for this to work, iOS 7 – Lucas Jul 07 '17 at 14:35
3

It looks like focus will work but only when directly called from a native event. calling focus using something like SetTimeout does not appear call up the keyboard. Control of the ios keyboard is very poor. Its not a good situation.

yodaisgreen
  • 2,310
  • 3
  • 22
  • 27
2

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.

adnan tariq
  • 197
  • 2
  • 13
1

With iOS 7 on iPad the only way that I was able to make this work was to use actually <textarea></textarea> instead of <input> field.

e.g.

<textarea onclick="this.setSelectionRange(0, 9999);">My text will be selected when textarea is clicked.</textarea>

How to prevent user from changing text inside area was more difficult, since is you make textarea readonly the selection trick won't work anymore.

Mikael Lepistö
  • 18,909
  • 3
  • 68
  • 70
1

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.

robocat
  • 5,293
  • 48
  • 65
-4

If you are using HTML5-compliant browsers, you can use placeholder="xxx" in your input tag. That should do the job.

Jonas G. Drange
  • 8,749
  • 2
  • 27
  • 38
DrMad
  • 9
  • 1