Ionut Bilica
Ionut Bilica

Reputation: 434

How to focus an input field on Android browser through javascript or jquery

I've tried $('#field').focus(), and any other method found on the internet. Nothing worked. I have a simple html that reproduces the problem.

<!DOCTYPE html> 
<html> 
    <head> 
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $('#field').focus();
            });
    </script>
</head> 
<body>
    <input type="text" id="field" name="field"/>
</body>
</html>

Please help!

Upvotes: 8

Views: 19104

Answers (3)

bbsimonbb
bbsimonbb

Reputation: 29002

click() or focus() alone 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. Soft keyboard popping nicely.

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

if (event.target != target) {
    target.focus();
    target.click();
}

Upvotes: 0

user1207504
user1207504

Reputation: 367

if you bind it to another click event it will work. This works for me:

    $(document).ready(function()
    {

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

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

Will pop up the software keyboard. trigger() will trigger any event you give it. In this case the default behaviour of clicking on the field == tap == focus == win! Note: this call is bound to another click event happening.

Upvotes: 1

woobione
woobione

Reputation: 358

Actually, the general javascript function "focus" is deactivated in the android browser. Hence, the jQuery focus function is deactivated since it's using the above.

Upvotes: 5

Related Questions