John
John

Reputation: 1

How can I set the focus automatically on a field in div?

I have a div where I input a search query:

<div id="search">
  <form method="get" action="http://www.bing.com/search">
   <input type="text"   name="q" size="31" maxlength="255" value="" />
   <input type="submit" value="Search" />
  </form>
 </div>

How can I set the focus automatically when the page loads?

Upvotes: 0

Views: 3910

Answers (3)

alex
alex

Reputation: 490283

That is very annoying. But if you must...

window.onload = function() {

   document.getElementById('search').getElementsByTagName('input')[0].focus();

}

I didn't change your HTML.

Upvotes: 2

Macy Abbey
Macy Abbey

Reputation: 3887

Make sure you give the input with a name of "q" an id of "q" as well.

Also note, the window onload event is not the greatest. If for example, an image tag fails to load the image, the window onload event will not fire. That is why frameworks like jquery have a $(document).ready() event handler.

<script type="text/javascript">
window.onload = function(){
    document.getElementById('q').focus();
}
</script>

Upvotes: 0

Marc W
Marc W

Reputation: 19241

<body onload="document.getElementById('q').focus()">

  <div id="search">
    <form method="get" action="http://www.bing.com/search">
     <input type="text" id="q" name="q" size="31" maxlength="255" value="" />
     <input type="submit" value="Search" />
    </form>
   </div>

</body>

Notice that I gave your input field an id attribute as well.

Upvotes: 0

Related Questions