Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 732
Ionut Bilica Avatar asked Jan 13 '12 22:01

Ionut Bilica


People also ask

How can input focus in JQuery?

Example 1: In this example the form input text field gets the focus as page loads by using focus() method . Here the input element is selected by input keyword in JQuery selector. | Set focus on a form input text field on page load. This input box gets the focus as the page loads.

How can you specify focus in an input field?

The autofocus attribute is a boolean attribute. When present, it specifies that an <input> element should automatically get focus when the page loads.

How can I set focus on an element in an HTML form using JavaScript?

To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.


2 Answers

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.

like image 131
woobione Avatar answered Oct 02 '22 07:10

woobione


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.

like image 29
user1207504 Avatar answered Oct 02 '22 08:10

user1207504