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

Discussion in 'ASP .Net' started by feng, Feb 19, 2004.

  1. feng

    feng Guest

    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
     
    feng, Feb 19, 2004
    #1
    1. Advertisements

  2. feng

    Fadi El-Eter Guest

    weird, this code should work. Remember, you have to put it on the onLoad
    event of the <body> tag.
     
    Fadi El-Eter, Feb 19, 2004
    #2
    1. Advertisements

  3. feng

    Fadi El-Eter Guest

    Here's a small html file containing a working example.
     
    Fadi El-Eter, Feb 19, 2004
    #3
  4. feng

    Jon Guest

    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
     
    Jon, Feb 19, 2004
    #4
  5. feng

    Maureen Guest

    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()">
     
    Maureen, Feb 19, 2004
    #5
  6. feng

    Rajiv R Guest

    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.
     
    Rajiv R, Feb 27, 2004
    #6
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.