46

I'm creating a mobile version of my site. There's a part of the site where a dialog pops up with a text input. Normally I would just use jQuery to bring focus to the text input, but that's not working. Here's what I'm trying:

$("#textinput").focus();
$("#textinput").click(); 
$("#textinput").trigger("tap"); //jQuery Mobile

None of them seem to work. Any ideas? I've been testing it on my DroidX. I'm using jQuery Mobile but I'm open to other libraries if they help.

Adam
  • 3,063
  • 5
  • 35
  • 49

3 Answers3

55

You can't, at least not in iOS (iPhone), and I believe Android as well. It's a usability issue that the keyboard should not be allowed to be triggered except by user input (it's just annoying if it's automatic).

There are a couple of ways I know of to get around this:

  • prompt() opens the keyboard
  • If you trigger the .focus() from within a .click() event (e.g. from opening your dialog), the keyboard shows up
  • 2
    Ah, makes sense. In theory it make sense from their point of view that the keyboard should only be up when the user brings focus to an element for usability reasons. However in the case where an input is the only thing on the screen and for usability reasons I want to automatically bring focus to that element the keyboard won't pop up. At any rate, thanks for your help. – Adam Jul 28 '11 at 16:02
  • 2
    One huge caveat is that is has to be a `click` event. Even though `tap` and `click` are basically the same, it has to be a `click` event or it won't open – dansch Sep 29 '13 at 00:26
  • But why oh why does trigging .focus() from within a *keyboard* event not work? – Michael Nov 29 '13 at 23:46
  • @Michael -- there are no keyboard events on an iphone unless the keyboard is already open :) –  Dec 01 '13 at 12:03
  • right i understand that. but if you call focus() on a different a different text input from a keyboard event, the on-screen keyboard *goes away*! – Michael Dec 01 '13 at 16:34
  • 2
    Can you elaborate on the `prompt()` method? Can it be used as workaround when you can't trigger `focus` from within a `click` event? – Petr Peller Mar 25 '14 at 15:07
  • 4
    @PetrPeller -- He was reffering to window.prompt() which displays a popup dialog box that prompts the visitor for input. It displays the keyboard but also the popup dialog, so you can't simpy use it for form inputs. [link](http://www.w3schools.com/jsref/met_win_prompt.asp) – Mihai MATEI Sep 04 '14 at 00:31
26

$("#textinput").focus();

Opening the keyboard by setting the focus to an input element, will only work if the focus is set within a "user context" (e.g. click, mousedown, mouseup).

From the "script context" (setTimeout, callback returned from an ajax call) the keyboard won't show up.

Tony Findeisen
  • 380
  • 4
  • 5
-1

you can use:

$(textFiled).trigger("focus");

you can put this code in some function that will trigger on opening some overlay, or when the document is ready.