How do you automatically set the focus to a textbox when a web page loads?

Mark Biek picture Mark Biek · Sep 5, 2008 · Viewed 360.4k times · Source

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?

Answer

Ben Scheirman picture Ben Scheirman · Sep 5, 2008

If 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.