3

I am creating a PhoneGap app. I have to set focus on a textarea on the pageload:

I have used

<body onload="newNoteOnLoad();">
<div class="container">
    <div class="header">
        <h1 id="noteHeader">
            New Note</h1>
        <a href="Books.html" class="back" id="back"></a><a href="#" class="done" id="bttnDone" onclick="addNewNote();">
        </a>
    </div>
    <div class="mainhelp">
        <p>
          <textarea id="txtNote" cols="115" rows="15"></textarea>
        </p>
    </div>    
</div>
<script type="text/javascript">
  alert('focus');
  document.getElementById("txtNote").focus();
</script>

in pageload function. But it didn't work for me. Can anyone help me out please?

Ilia Ross
  • 13,086
  • 11
  • 53
  • 88
Sreehari
  • 515
  • 3
  • 11
  • 27

3 Answers3

15

As of iOS 6, the UIWebView class has a property called "keyboardDisplayRequiresUserAction". If you want to set this to false, you can access it via your phonegap config.xml:

<preference name="KeyboardDisplayRequiresUserAction" value="false" />

The default value is true, which means that programmatically focussing any text form element just won't work.

More here: http://community.phonegap.com/nitobi/topics/calling_focus

adamvert
  • 615
  • 5
  • 15
1

You are referring to the element that is not loaded to the DOM yet. For these purposes, jQuery, for example, has .ready() event. Load the same script right under the 'myControl' element in HTML and see if it works or use jQuery for doing this.

JavaScript solution works like this, when you load it after the HTML element that you're referring to, e.g.:

  <textarea id="myControl"></textarea>
    <script>
      document.getElementById('myControl').focus(); 
    </script>

Using jQuery it would look like this and you could load it anywhere on the page:

$(document).ready(function() {
   $('#myControl').focus();
});
Ilia Ross
  • 13,086
  • 11
  • 53
  • 88
1

If you want the keyboard to show you will have big trouble cause the focus event get's fired async. I have only had luck getting the keyboard up on user input's such as touchstart, touchend & click

Andreas Louv
  • 46,145
  • 13
  • 104
  • 123