JavaScript: How to set focus on a textbox in a HTML form?

  • Thread starter Thread starter feng
  • Start date Start date
F

feng

Hi,

I have a aspx page that contains a textbox. When the page
loads, it's always the browser's address bar or other
browser controls has the focus. What I want however, is to
let the textbox have the focus, but I don't know how to do
it. I tried things like:
window.document.Form1.MyTxtBox.focus(); but that didn't
work. Can someone show me how?

Thanks
 
weird, this code should work. Remember, you have to put it on the onLoad
event of the <body> tag.
 
Hi,
it should work - assuming this is the first (and/or only) form on the page
try it like this
<body onload="document.forms[0].MyTxtBox.focus();">
the second form would be document.forms[1] etc
or you can try
<body onload="document.forms[0].elements[0].focus();">
elements[0] being the first form field elements[1] the second etc....

Jon
 
This is what I've used in the past on regular html pages, although
I've never tried it on an aspx page:

<body onload="document.Form1.MyTxtBox.focus()">
 
Page.RegisterStartupScript("SetFocus", "<script language=""Jscript"" > document.getElementById(""Textbox1"").focus(); </Script>")

--
Cheers!
Rajiv. R
Rajspace.Org

Here's a small html file containing a working example.
 
Back
Top