最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

In a web-page I've got a search field. I've added a "clear" button so that users can clear the search field and start again. As a convenience, I focus the search field's text box and the cursor does appear in the box. However the soft keyboard does not seem to show up on android devices that use the default browser. In iOS and Opera Mobile it works as I'd expect.

Is there an additional method I can call that will cause the keyboard to show on Android's browser so the user can start typing right away?

function clear_search() {
    if($('#searchinput').val()) {
        $('#searchinput').val('');
    }
    $('#searchinput').focus();
}

In a web-page I've got a search field. I've added a "clear" button so that users can clear the search field and start again. As a convenience, I focus the search field's text box and the cursor does appear in the box. However the soft keyboard does not seem to show up on android devices that use the default browser. In iOS and Opera Mobile it works as I'd expect.

Is there an additional method I can call that will cause the keyboard to show on Android's browser so the user can start typing right away?

function clear_search() {
    if($('#searchinput').val()) {
        $('#searchinput').val('');
    }
    $('#searchinput').focus();
}
Share Improve this question edited May 16, 2011 at 17:23 newz2000 asked May 16, 2011 at 16:29 newz2000newz2000 2,6401 gold badge24 silver badges31 bronze badges 0
Add a comment  | 

3 Answers 3

Reset to default 5

this question is similar to How to focus an input field on Android browser through javascript or jquery

Anyway, as you already have a click event to work with, this should sort you out:

$(document).ready(function() {
    $('#field').click(function(e){ $(this).focus(); });

    $('#button').click(function(e) {
        $('#field').trigger('click');
    });
})     

Of course you DO need a click event triggering this. Just focussing without an event doesnt seem to work. The above works for me on the standard browser on android 4 and shows the soft keyboard.

click() on its own is not enough. You need to focus() then click(). Beware of endless loops if your script is triggered by an onclick() on a containing element. 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();
}

I am not 100% sure but I think it can`t be done (at least until android 2.2) from javascript. If you are using phonegap you can use this here: https://github.com/phonegap/phonegap/wiki/How-to-show-and-hide-soft-keyboard-in-Android

发布评论

评论列表(0)

  1. 暂无评论