Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
}
like image 654
newz2000 Avatar asked May 16 '11 16:05

newz2000


People also ask

How do I get my Android keyboard to automatically appear?

Solution 3: Always show they KeyboardgetWindow(). setSoftInputMode( WindowManager. LayoutParams. SOFT_INPUT_STATE_ALWAYS_VISIBLE);

How can I hide the Android keyboard using JavaScript?

To hide the Android keyboard using JavaScript, we set hide it after we focus on the input. const field = document. createElement("input"); field. setAttribute("type", "text"); document.

What is soft keyboard in Android?

The soft keyboard (also called the onscreen keyboard) is the main input method on Android devices, and almost every Android developer needs to work with this component at some point.

How do I close keyboard on Android programmatically?

Hiding the Soft Keyboard Programmatically You can force Android to hide the virtual keyboard using the InputMethodManager, calling hideSoftInputFromWindow, passing in the token of the window containing your edit field. This will force the keyboard to be hidden in all situations.


2 Answers

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.

like image 69
user1207504 Avatar answered Oct 27 '22 23:10

user1207504


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();
}
like image 31
bbsimonbb Avatar answered Oct 27 '22 23:10

bbsimonbb