16

I have some custom web components in my mobile web app, whereas I need to manually fire 'focus' events on a field, to simulate the 'NEXT' functionality in the Android soft keyboard feature. ( using Galaxy S3 native browser ).

However, when I manually fire a focus event on a 'select' field, the native soft keyboard does not show. I have to subsequently click on the field to get it to show. (In IOS, of course, it works just fine).

So I'm wondering, if a 'focus' event doesn't trigger the soft keyboard to open, what JS event will ???

I am not using phonegap so I'm hoping there's a way without it.

Thanks for any help!!!

29er
  • 8,595
  • 12
  • 48
  • 65

3 Answers3

21

Here's a link from StackOverflow:

Showing Android's soft keyboard when a field is .focus()'d using javascript

Just focussing without an event doesnt seem to work. - you DO need a click event triggering this.

$(document).ready(function() {
    $('#field').click(function(e){
        $(this).focus();
    });
    $('#button').click(function(e) {
        $('#field').trigger('click');
    });
});
Community
  • 1
  • 1
paulsm4
  • 114,292
  • 17
  • 138
  • 190
  • 2
    Thank you. Im using pure javascript instead of jquery, but the concept worked :) – 29er Mar 18 '13 at 02:35
  • 1
    Is it possible show keyboard without real clicking? I tried to hide button and click programmaticaly, but also had no success: http://jsfiddle.net/alex_myronov/e5JcP/8/ Also tried without buttons, by triggering click on input... – alex.mironov Jan 10 '14 at 16:35
  • @alex.mironov: check this out. http://stackoverflow.com/questions/6837543/show-virtual-keyboard-on-mobile-phones-in-javascript – oak Feb 27 '14 at 09:36
  • 2
    This works, as long as it was initiated from a click (from a different button, etc). It does not work if it was triggered by a different event, for example a setTimeout() or other random events – Adam Tegen Apr 05 '15 at 03:30
1

You can do this by calling focus() then click() on the input. No need for jquery. Beware of endless loops if your script is triggered by an onclick() on a containing element. Make sure as well that this script is triggered by some user interaction. It won't work from document.onload(), or from a setTimeout(). It's also fragile with things like simultaneous style changes on the elements. The script below is working for me on Chrome for android 58 and Safari mobile 602.1.

var target = document.getElementsByTagName("input")[0];

if (event.target != target) {
    target.focus();
    target.click();
}
bbsimonbb
  • 27,056
  • 15
  • 80
  • 110
0

Vanilla JS solution:

let button = document.getElementById("b");
let input = document.getElementById("i");

// Keyboard opens when focusing the input from a click listener
button.addEventListener("click", () => {
  input.focus();
});

// Input field gets focus but keyboard doesn't open.
setTimeout(() => {
  input.focus();
}, 1000);
Ambrus Tóth
  • 552
  • 6
  • 14