views:

8463

answers:

9

OK, this has to be insanely easy but I honestly don't know how to do it. How do you automatically set the focus to a textbox when a web page loads?

Is there an HTML tag to do it or does it have to be done via javascript?

+7  A: 

You need to use javascript:

<BODY onLoad="document.getElementById('myButton').focus();">


@Ben notes that you should not add event handlers like this. While that is another question, he recommends that you use this function:

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

And then put a call to addLoadEvent on your page and reference a function the sets the focus to you desired textbox.

Espo
+1  A: 
<html>  
<head>  
<script language="javascript" type="text/javascript">  
function SetFocus(InputID)  
{  
   document.getElementById(InputID).focus();  
}  
</script>  
</head>  
<body onload="SetFocus('Box2')">  
<input id="Box1" size="30" /><br/>  
<input id="Box2" size="30" />  
</body>  
</html>  
Joel Coehoorn
Too many `"`. You need: `<body onload="SetFocus('Box2')">`
dave1010
A: 

I was hoping for an HTML tag but you can't get javascript much easier than that.

Thanks Espo.

Mark Biek
+19  A: 

Any javascript book will tell you not to put handlers on the body element like that.

I'f you're using jquery:

$(function() {
  $("#Box1").focus();
});

or prototype:

Event.observe(window, 'load', function() {
  $("Box1").focus();
});

or plain javascript:

window.onload = function() {
  document.getElementById("Box1").focus();
};

though keep in mind that this will replace other on load handlers, so look up addLoadEvent() in google for a safe way to append onload handlers rather than replacing.

Ben Scheirman
Why not put handlers on the body element? Any reference? Thanks
disown
Because it's much cleaner to separate javascript from the HTML. You should be adding scripting behavior to visual elements in your HTML.
Ben Scheirman
+4  A: 

Using plain vanilla html and javascript

<input type='text' id='txtMyInputBox' />


<script language='javascript' type='text/javascript'>
function SetFocus()
{
    // safety check, make sure its a post 1999 browser
    if (!document.getElementById)
    {
        return;
    }

    var txtMyInputBoxElement = document.getElementById("txtMyInputBox");

    if (txtMyInputBoxElement != null)
    {
        txtMyInputBoxElement.focus();
    }
}
SetFocus();
</script>

For those out there using the .net framework and asp.net 2.0 or above, its trivial. If you are using older versions of the framework, you'd need to write some javascript similar to above.

In your OnLoad handler (generally page_load if you are using the stock page template supplied with visual studio) you can use:

C#

protected void PageLoad(object sender, EventArgs e)
{
    Page.SetFocus(txtMyInputBox);
}

VB.NET

Protected Sub PageLoad(sender as Object, e as EventArgs)

    Page.SetFocus(txtMyInputBox)

End Sub

(* Note I removed the underscore character from the function name that is generally Page_Load since in a code block it refused to render properly! I could not see in the markup documentation how to get underscores to render unescaped.)

Hope this helps.

Jon
+1  A: 

As a general advice, I would recommend not stealing the focus from the address bar. (Jeff already talked about that.)

Web page can take some time to load, which means that your focus change can occur some long time after the user typed the pae URL. Then he could have changed his mind and be back to url typing while you will be loading your page and stealing the focus to put it in your textbox.

That's the one and only reason that made me remove Google as my start page.

Of course, if you control the network (local network) or if the focus change is to solve an important usability issue, forget all I just said :)

Vincent Robert
I agree with you in some cases. However, in my specific case, I'm popping up a little div which only one input box. The user is supposed to enter something and the immediately close the div so setting the focus is handy.
Mark Biek
A: 

WOW!!! Many other road to focus text box, thanks all.

restroika
+1  A: 

In HTML there's an autofocus attribute to all form fields. There's a good tutorial on it in Dive Into HTML 5. Unfortunately it's currently not supported by Firefox and IE.

To use the HTML 5 attribute and fall back to a JS option:

<input id="my-input" autofocus="autofocus" />
<script>
  if (!("autofocus" in document.createElement("input"))) {
    document.getElementById("my-input").focus();
  }
</script>

No jQuery, onload or event handlers are required, because the JS is below the HTML element.

Edit: another advantage is that it works with JavaScript off in some browsers and you can remove the JavaScript when you don't want to support older browsers.

dave1010
A: 

IMHO, the 'cleanest' way to select the First, visible, enabled text field on the page, is to use jQuery and do something like this:

$(document).ready(function() { $('input:text[value=""]:visible:enabled:first').focus(); });

Hope that helps...

revive