Mark Biek Mark Biek - 9 days ago 4
Javascript Question

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

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?

Answer

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.