How to Setting Focus of Web TextBox control

Discussion in 'ASP.NET / ASP.NET Core' started by albanello, Dec 30, 2005.

Thread Status:
Threads that have been inactive for 5 years or longer are closed to further replies. Please start a new thread.
  1. Hi
    I have two TextBoxes and one button in a WEB Application. When the page opens the first time I don't see the focus on anything. when I press the tab key the Focus goes to the first TextBox.

    How do I set the Focus to the first TextBox when the page loads ?

    I am using Visual Studio/Visual Basic/ASP.net

    I have been searching and can not find relative to doing it in ASP.NET

    I this possible

    albanello
     
  2. The only way is to use javascript. Either add the sub below to a class & call it during the page load event or create a javascript function that does the same (adding the call to this function to your body onload event):

    Public Sub SetFocus(ByVal ctrl As Control)
    Dim s As New System.Text.StringBuilder() 'add Imports System.Text to use this
    s.Append("<SCRIPT LANGUAGE='JavaScript'>")
    s.Append("function SetInitialFocus()")
    s.Append("{")
    '*#*#*#*#*#*#*#*
    s.Append(" if(document.")
    Dim p As Control = ctrl.Parent
    While Not TypeOf p Is System.Web.UI.HtmlControls.HtmlForm
    p = p.Parent
    End While
    s.Append(p.ClientID)
    s.Append("['")
    s.Append(ctrl.UniqueID)
    s.Append("']){")

    '*#*#*#*#*#*#*#*#
    s.Append(" document.")
    p = ctrl.Parent
    While Not TypeOf p Is System.Web.UI.HtmlControls.HtmlForm
    p = p.Parent
    End While
    s.Append(p.ClientID)
    s.Append("['")
    s.Append(ctrl.UniqueID)
    s.Append("'].focus();} ")
    s.Append("}")
    s.Append(" window.onload = ")
    s.Append("SetInitialFocus; ")
    s.Append("</SCRIPT>")
    ctrl.Page.RegisterClientScriptBlock("InitialFocus", s.ToString())
    End Sub
     
  3. UKBuckeye


    Wow that is a lot of code. I found this:


    <html>
    <head>
    <script language="JavaScript">
    function setFocus()
    {
    frmInfo.name.focus();
    }
    </script>
    </head>

    <form id="frmInfo">
    Name: <input type="text" id="name" />
    Age: <input type="text" id="age" />
    </form>
    </body>
    </html>


    Dosn't this do the same thing. As I understand your code it appears you are dynamically creating about the same thing. Can you explain what it is about your code that is different. I can see that your code would be reusable ie: you could call it with ANY control


    Incidently the code I have shown appears to work but the cursor does not show. When I run my code nothing appearsto be infocus. When I press the Tab key the second tab index gets focus. So it appears the first tab index has focus BUT the cursor is not showing.


    Thank for your responce


    albanello


    Thank's for you
     
  4. Hi UKBuckeye


    Well I tried what you suggested in your last post. I added to the body tag onload="SetFocus()" and it still does not set the focus to the TextBox. When the page comes up nothing appears to be in focus. After the first Tab key press the cursor appears in the txtUserNameID TextBox (I have the Tagindex for this textbox set to 1)


    This is in the head section with script tags around it


    .function SetFocus()
    .{

    .if(document.getElementById["txtUserNameID"])
    .{

    .document.getElementById["txtUserNameID"].focus();
    .document.write("Focus() executed");</BLOCKQUOTE>
    .}
    .document.write("SetFocus() executed");</BLOCKQUOTE>
    .}

    I removed the onload in the body tag and placed this is at the End of the body section with script tags also
    .SetFocus();
    .document.write("SetFocus() called");

    NOTE the period is just there so I can format in this text editor


    The document.write that where displayed are "SetFocus() executedSetFocus() called" IN THAT ORDER

    What else could cause it to not work ? I have to be doing something wrong.

    Appreciate your help
    albanello
     
  5. Hi,
    You're correct - they both do pretty much the same thing with the vb.net code simply becoming reusable from project to project. Also the script built by the vb sub checks for the existence of the control before applying the focus - always worth doing imho.

    If you want to just use javascript then I prefer the following script. See if this works better for you.

    function SetFocus()
    {

    if(document.getElementById["myTextBoxName"])
    {

    document.getElementById["myTextBoxName"].focus();</BLOCKQUOTE>
    }</BLOCKQUOTE>
    }
     
  6. Hi,


    Because of the order of the script execution I it means that you don't have the correct name/id of your textbox (the script does not find the control).


    Do you have the textbox in a control (.ascx) file? If so you need ["myControl:myTextbox"] as the ID.


    Easiest way to tell is to run your app, then view source - find your textbox &amp; see what ID has been generated by ASP.Net.


    Then make sure the name in the javascript matches exactly and try again.
     
  7. Hi UKBuckeye


    I agreeSetFocus() is not seeing the TextBox. I changed the ["txtUserNameID"] to ["Form1:txtUserNameID"].


    I tried onload="SetFocus()" in the body tag andcalling SetFocus() as thelast thing before the closing Form tag. The result was the same as stated in my last post.


    The only thing I noticed, in your last postyou said "Do you have the textbox in a control (.ascx) file?". My TextBox is in a (.aspx) file.


    I looked at the view source and it appears correct.


    sorry to be a pain but appreciate your help


    albanello
     
  8. Albanello, my bad - change the [ character to (

    this, for example, works:

    function SetFocus()
    {

    if(document.getElementById("txtFocus1"))
    {

    alert("I found your textbox!");
    document.getElementById("txtFocus1").focus(); </BLOCKQUOTE>
    }
    else
    {

    alert("I did not find your textbox!"); </BLOCKQUOTE>
    } </BLOCKQUOTE>
    }
     
  9. There's no reason adding the alert makes it work/not work so I'm not sure why the script doesn't work for you.
    Alternatively take a look at the thread http://community.discountasp.net/default.aspx?f=15&amp;m=6890to see a similar way to implement setting the focus.
    For your tab order make sure the 1st control's tabindex propertyis set to 1 (not zero).
     
  10. Hi UKBuckeye


    I have good news and I have bad news


    Good News


    ********


    This Set the Focus: (Remember the period is just for format in this editor)


    .function SetFocus()


    .{



    .if(document.getElementById("txtUserNameID"))


    .{



    .alert("I found your textbox!");


    .document.getElementById("txtUserNameID").focus(); </BLOCKQUOTE>


    .}


    .else


    .{



    .alert("I did not find your textbox!"); </BLOCKQUOTE>
    .}</BLOCKQUOTE>


    .}


    GOT alert box "I found your textbox!"


    Bad News


    *******


    This did not Set the Focus


    .function SetFocus()


    .{



    .if(document.getElementById("txtUserNameID"))


    .{



    .document.getElementById("txtUserNameID").focus(); </BLOCKQUOTE>


    .}


    .else


    .{



    .alert("I did not find your textbox!"); </BLOCKQUOTE>
    .}</BLOCKQUOTE>


    .}


    DID NOT GET alert box "I did not find your textbox!"


    With the alert message "I found your textbox!"it worked. With out the alert message "I found your textbox!"it did NOT set the Focus ????????


    This is driving me nuts. How can something so simple be so much trouble !


    Any ideas why the alert() message would cause a differents.


    When it does not work the focus is someplace else the first tab press puts the focus at the correct TextBox. I think the alert() is putting the focus to the page so that the Textbox SHOWS FOCUS.


    Any ideas are greatly appreciates Thanks


    albanello
     
  11. UKBuckeye


    Correction:


    "When it does not work the focus is someplace else the first tab press puts the focus at the correct TextBox"


    Should have said:


    When it does not work the focus is someplace else the first tab press puts the focus at thesecond TextBox. It like the TextBox that is suppose to have focus has focus BUT the cursor is not displayed. I tried to place some text but nothing appeared in the first TextBox ????


    One more note if I put the Alert "I found your Text Box" AFTER the focus() the first TextBox did not have focus


    albanello



    Post Edited (albanello) : 1/5/2006 3:01:11 AM GMT
     
Thread Status:
Threads that have been inactive for 5 years or longer are closed to further replies. Please start a new thread.

Share This Page