Set Focus on PostBack

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • erickme
    New Member
    • Jul 2007
    • 8

    Set Focus on PostBack

    Well I wasn't to sure if post this on the javascript forum or here, but since is an error that probably I got because something related to my ASP.Net code I decided to posted here.

    Ok my problem is that I need to set focus on a textbox everytime the page is loaded. Maybe you already thinking what I thought at first, that with a textbox.setFocu s() that will do it. Nop this is .Net Framework 1.1 and textbox.setFocu s() didn't exist back then. So I did the other simple thing add a javascript on body onload="documen t.getElementByI d(<%= txtPCode.Client ID %>).focus(). It works on page load but not in postback. I really have try a couple of other things like adding this function in the .vb
    Code:
     
            Private Sub SetFocus(ByVal ClientID As String)
                Dim Script As New System.Text.StringBuilder
                'Dim ClientID As String = FocusControl.ClientID
                With Script
                    .Append("<script language='javascript'>")
                    .Append("document.getElementById('")
                    .Append(ClientID)
                    .Append("').focus();")
                    .Append("</script>")
                End With
                RegisterStartupScript("setFocus", Script.ToString())
            End Sub
    and calling it in from the Page_Load like this SetFocus(textbo x.ClientID).

    Anyway nothing of this have work to set the focus of the textbox on the page post back.

    Anyone have another idea?

    Thanks,

    Erick
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    Originally posted by erickme
    Well I wasn't to sure if post this on the javascript forum or here, but since is an error that probably I got because something related to my ASP.Net code I decided to posted here.

    Ok my problem is that I need to set focus on a textbox everytime the page is loaded. Maybe you already thinking what I thought at first, that with a textbox.setFocu s() that will do it. Nop this is .Net Framework 1.1 and textbox.setFocu s() didn't exist back then. So I did the other simple thing add a javascript on body onload="documen t.getElementByI d(<%= txtPCode.Client ID %>).focus(). It works on page load but not in postback. I really have try a couple of other things like adding this function in the .vb
    Code:
     
            Private Sub SetFocus(ByVal ClientID As String)
                Dim Script As New System.Text.StringBuilder
                'Dim ClientID As String = FocusControl.ClientID
                With Script
                    .Append("<script language='javascript'>")
                    .Append("document.getElementById('")
                    .Append(ClientID)
                    .Append("').focus();")
                    .Append("</script>")
                End With
                RegisterStartupScript("setFocus", Script.ToString())
            End Sub
    and calling it in from the Page_Load like this SetFocus(textbo x.ClientID).

    Anyway nothing of this have work to set the focus of the textbox on the page post back.

    Anyone have another idea?

    Thanks,

    Erick
    You're on the right track Erick.

    I have solved this same problem in the past but it is a matter of where you place your JavaScript call... You need to set the focus in the OnLoad in your <body> tag. This means that you have to place your JavaScript in the <head> section of your page.

    You'll need something like:
    [code=javascript]
    <script language=javasc ript type="text/javascript">
    onload = function()
    { /*get all input elements on page */
    var allinputelement s=document.getE lementsByTagNam e('input');
    var len= A.length;
    /* setting the focus to the first input element that allows focus*/

    for(var i = 0; i < len; i++)
    {
    try{
    allinputelement s[i].focus();
    break;
    }
    catch(error)
    {/*focus wasn't set*/}
    }

    }
    </script>
    [/code]
    please note that my javascript function is just an example and may not actually work


    Instead of setting the focus on the first control that allows focus, you could register a hidden field with the name of the control in your Server Side code and set the focus to that field using the GetElementByID( 'nameOfYourCont rolStoredInTheH iddenFieldYouRe gistered').

    Keep trying :)

    You'll get it!
    Just remember that your JS must be declared in the Head section of your web page in order for it to work on load :)

    -Frinny

    Comment

    • nateraaaa
      Recognized Expert Contributor
      • May 2007
      • 664

      #3
      Originally posted by erickme
      Well I wasn't to sure if post this on the javascript forum or here, but since is an error that probably I got because something related to my ASP.Net code I decided to posted here.

      Ok my problem is that I need to set focus on a textbox everytime the page is loaded. Maybe you already thinking what I thought at first, that with a textbox.setFocu s() that will do it. Nop this is .Net Framework 1.1 and textbox.setFocu s() didn't exist back then. So I did the other simple thing add a javascript on body onload="documen t.getElementByI d(<%= txtPCode.Client ID %>).focus(). It works on page load but not in postback. I really have try a couple of other things like adding this function in the .vb
      Code:
       
              Private Sub SetFocus(ByVal ClientID As String)
                  Dim Script As New System.Text.StringBuilder
                  'Dim ClientID As String = FocusControl.ClientID
                  With Script
                      .Append("<script language='javascript'>")
                      .Append("document.getElementById('")
                      .Append(ClientID)
                      .Append("').focus();")
                      .Append("</script>")
                  End With
                  RegisterStartupScript("setFocus", Script.ToString())
              End Sub
      and calling it in from the Page_Load like this SetFocus(textbo x.ClientID).

      Anyway nothing of this have work to set the focus of the textbox on the page post back.

      Anyone have another idea?

      Thanks,

      Erick
      This looks a lot like what you have already tried but this code works for me. Put this in your page_load event.

      [CODE=vbnet]Page.RegisterSt artupScript("Se tFocus", ("<script>docum ent.getElementB yId('" + (txtfirstName.C lientID + "').focus() ;</script>")))[/CODE]

      Nathan

      Comment

      • erickme
        New Member
        • Jul 2007
        • 8

        #4
        Thanks, but neither worked.

        I don't know what else to try.

        Comment

        • Frinavale
          Recognized Expert Expert
          • Oct 2006
          • 9749

          #5
          Originally posted by erickme
          Thanks, but neither worked.

          I don't know what else to try.
          Please post your exact code so that we can see what you have done.
          I don't know why it wouldn't have worked for you.

          We'll get you through this :)

          -Frinny

          Comment

          • Plater
            Recognized Expert Expert
            • Apr 2007
            • 7872

            #6
            You could try viewing the source on say a google page and seeing what they do?

            Comment

            • Frinavale
              Recognized Expert Expert
              • Oct 2006
              • 9749

              #7
              I did mention that the code I posted wasn't working 100%.
              If you had copied and pasted into your code it would not have worked.

              Did you look at the error that was generated by this JavaScript code?

              This should probably correct the mistake:
              [code=javascript]
              <script language=javasc ript type="text/javascript">
              onload = function()
              { /*get all input elements on page */
              var allinputelement s=document.getE lementsByTagNam e('in put');
              var len= allinputelement s.length;
              /* setting the focus to the first input element that allows focus*/
              for(var i = 0; i < len; i++)
              {
              try{
              allinputelement s[i].focus();
              break;
              }
              catch(error)
              {/*focus wasn't set*/}

              }
              }
              </script>
              [/code]
              Can you see what I changed?

              I still haven't tested this but I'm pretty sure it'll work now.
              You're still going to have to put it in the <head> section of your HTML.



              -Frinny

              Comment

              • Plater
                Recognized Expert Expert
                • Apr 2007
                • 7872

                #8
                I am a little confused. Do all the html elements not still have the .focus() in javascript?
                [code=html]
                <body onload="myobj.f ocus()">
                [/code]
                That seems like it should work regardless of postback behavior?
                (Unless of course your making behind the scenes calls ala AJAX)

                Comment

                • Frinavale
                  Recognized Expert Expert
                  • Oct 2006
                  • 9749

                  #9
                  Originally posted by Plater
                  I am a little confused. Do all the html elements not still have the .focus() in javascript?
                  [code=html]
                  <body onload="myobj.f ocus()">
                  [/code]
                  That seems like it should work regardless of postback behavior?
                  (Unless of course your making behind the scenes calls ala AJAX)

                  http://javascript.internet.com/page-...us-onload.html
                  Some objects (like hidden fields) don't let you set the focus on them though. That's why there's a Try/Catch block in the loop through all the input elements in my JavaScript function.

                  But you're right, it should work regardless of the postback behaviour when used like this (with the exception to asynchronous requests to the server using partial page update of course).

                  Comment

                  • Plater
                    Recognized Expert Expert
                    • Apr 2007
                    • 7872

                    #10
                    Why all this talk of hidden textboxes?
                    He knows the name of the textbox.
                    It's not hidden.
                    mynothiddentext box.focus()

                    (Assuming one uses the NAME property, otherwise you'll need the getElementById( ))

                    Comment

                    • Frinavale
                      Recognized Expert Expert
                      • Oct 2006
                      • 9749

                      #11
                      Originally posted by Plater
                      Why all this talk of hidden textboxes?
                      He knows the name of the textbox.
                      It's not hidden.
                      mynothiddentext box.focus()

                      (Assuming one uses the NAME property, otherwise you'll need the getElementById( ))
                      Hmm I had to read the question again.
                      Maybe this person's using an Ajax call to do a partial page update?

                      Comment

                      • erickme
                        New Member
                        • Jul 2007
                        • 8

                        #12
                        I'm tired of looking for the problem. I didn't create the code, it was the guy before me so maybe he have something that it's not allowing this to work. Here is the code if anyone can figured it out.

                        [CODE=vbnet]
                        Imports System.Data.Odb c

                        Namespace ASPNET.StarterK it.Portal

                        Public Class ProductLookUpPa ge
                        'Inherits System.Web.UI.P age
                        Inherits ASPNET.StarterK it.Portal.Porta lPage
                        Protected WithEvents lnkReturn0 As System.Web.UI.W ebControls.Link Button
                        Protected WithEvents lnkReturn1 As System.Web.UI.W ebControls.Link Button

                        Protected WithEvents phBanner As System.Web.UI.W ebControls.Plac eHolder
                        Protected WithEvents lblTitle As System.Web.UI.W ebControls.Labe l
                        Protected WithEvents cmdLocate As System.Web.UI.W ebControls.Butt on
                        Protected WithEvents txtPCode As System.Web.UI.W ebControls.Text Box
                        Protected WithEvents vsPCode As System.Web.UI.W ebControls.Vali dationSummary
                        Protected WithEvents rfvPCode As System.Web.UI.W ebControls.Requ iredFieldValida tor
                        Protected WithEvents revPCode As System.Web.UI.W ebControls.Regu larExpressionVa lidator
                        Protected WithEvents cvPCode As System.Web.UI.W ebControls.Cust omValidator
                        Protected WithEvents dlProductNumber s As System.Web.UI.W ebControls.Data List
                        Protected WithEvents lblPCodeValue As System.Web.UI.W ebControls.Labe l
                        Protected WithEvents lblDescValue As System.Web.UI.W ebControls.Labe l
                        Protected WithEvents lblSizeValue As System.Web.UI.W ebControls.Labe l
                        Protected WithEvents lblWHHead As System.Web.UI.W ebControls.Labe l
                        Protected WithEvents lblWHQty As System.Web.UI.W ebControls.Labe l
                        Protected WithEvents lblStoreHead As System.Web.UI.W ebControls.Labe l
                        Protected WithEvents lblStoreQty As System.Web.UI.W ebControls.Labe l
                        Protected WithEvents btnPriceIt As System.Web.UI.H tmlControls.Htm lInputButton
                        Protected WithEvents spnContent As System.Web.UI.H tmlControls.Htm lGenericControl

                        #Region " Web Form Designer Generated Code "

                        'This call is required by the Web Form Designer.
                        <System.Diagnos tics.DebuggerSt epThrough()> Private Sub InitializeCompo nent()

                        End Sub

                        Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArg s) Handles MyBase.Init
                        'CODEGEN: This method call is required by the Web Form Designer
                        'Do not modify it using the code editor.
                        InitializeCompo nent()
                        End Sub

                        #End Region

                        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArg s) Handles MyBase.Load
                        Trace.Warn("Def ault.aspx.vb", "Called Page_Load()")
                        'DO NOT remove this line
                        'This is what loads the banner into the top
                        phBanner.Contro ls.Add(Page.Loa dControl("../../../DesktopPortalBa nner.ascx"))

                        '07/20/07
                        SetFocus(txtPCo de.ClientID)

                        'Counteract the DHTML onclick event assigned to the Look-Up Command Button
                        txtPCode.Attrib utes.Add("onfoc us", "document.forms (0).cmdLookup.d isabled = false;")

                        ' 03/16/05 WNS Added PriceIt
                        btnPriceIt.Visi ble = False
                        Page.RegisterHi ddenField("__EV ENTTARGET", cmdLocate.Clien tID)
                        If Page.IsPostBack = False Then
                        ' Store URL Referrer to return to portal
                        Try
                        ViewState("UrlR eferrer") = Request.UrlRefe rrer.ToString()
                        Catch ex As Exception
                        Dim clsApp As New CustomAppSettin gs
                        ViewState("UrlR eferrer") = clsApp.GetAppSe tting("StoreTab _Url")
                        End Try

                        Page.RegisterHi ddenField("__EV ENTTARGET", cmdLocate.Clien tID)

                        If Request.Params( "pcode") <> "" Then
                        Dim clsProducts As New ABCProducts
                        If clsProducts.IsV alidPCode(Reque st.Params("pcod e")) Then
                        txtPCode.Text = Request.Params( "pcode")
                        LocateProduct()
                        End If
                        End If

                        End If
                        RegisterStartup Script("SetFocu s", ("<script>docum ent.getElementB yId('txtPCode') .focus();</script>"))

                        End Sub

                        'DO NOT remove this return procedure
                        Private Sub lnkReturn_Click (ByVal sender As System.Object, ByVal e As System.EventArg s) Handles lnkReturn0.Clic k, lnkReturn1.Clic k
                        'Return to Portal
                        Response.Redire ct(CType(ViewSt ate("UrlReferre r"), String))
                        End Sub

                        Private Sub cmdLocate_Click (ByVal sender As System.Object, ByVal e As System.EventArg s) Handles cmdLocate.Click
                        'A PCode has been entered and the submit button clicked

                        'Query the SIRBALP by PCode and load into DataSet
                        If Page.IsValid Then
                        LocateProduct()
                        End If

                        End Sub

                        Public Sub ValidatePCode(B yVal sender As Object, ByVal e As ServerValidateE ventArgs)
                        Try
                        Dim intTest As Integer = txtPCode.Text
                        Catch ex As Exception
                        e.IsValid = False
                        Exit Sub
                        End Try

                        'July 11, 2007
                        'Validates PCODE against AS400 to see if is valid
                        Dim sqlCmd As String = "SELECT * FROM ABCPROD.INVMSTP WHERE (PCODE = " & txtPCode.Text & ") "
                        Dim conn As New OdbcConnection( System.Configur ation.Configura tionSettings.Ap pSettings("AS40 0"))
                        Dim cmd As New OdbcCommand(sql Cmd, conn)
                        conn.Open()
                        Dim AS400reader As OdbcDataReader = cmd.ExecuteRead er

                        AS400reader.Rea d()

                        If AS400reader.Has Rows Then
                        e.IsValid = True
                        Else
                        e.IsValid = False
                        End If
                        End Sub

                        Private Sub LocateProduct()
                        txtPCode.Text.T rim()

                        Dim sqlCmd As String = "SELECT STORE_NO, PCODE, END_QTY, S#STAT " & _
                        "FROM ABCPROD.SIRBALP , ABCPROD.STRMSTP " & _
                        "WHERE ((ABCPROD.SIRBA LP.STORE_NO = ABCPROD.STRMSTP .STRNO) " & _
                        "AND (S#STAT = 'A')) " & _
                        "AND (PCODE = " & txtPCode.Text & ") " & _
                        "AND (STORE_NO <> 10) " & _
                        "AND (STORE_NO <> 11) " & _
                        "AND (STORE_NO < 219) " & _
                        "AND (END_QTY > 0) " & _
                        "ORDER BY STORE_NO, PCODE, END_QTY"

                        Dim conn As New OdbcConnection( System.Configur ation.Configura tionSettings.Ap pSettings("AS40 0"))
                        Dim cmd As New OdbcCommand(sql Cmd, conn)
                        cmd.CommandType = CommandType.Tex t
                        Dim da As New OdbcDataAdapter (cmd)
                        Dim ds As New DataSet
                        da.Fill(ds)

                        cmd.CommandText = "SELECT PCODE, ASIZE, DESC, OHQTY " & _
                        "FROM ABCPROD.INVMSTP " & _
                        "WHERE (PCODE = " & txtPCode.Text & ") "
                        da.SelectComman d = cmd
                        da.Fill(ds, "Product")

                        lblPCodeValue.T ext = ds.Tables("Prod uct").Rows(0).I tem("PCODE")
                        lblDescValue.Te xt = ds.Tables("Prod uct").Rows(0).I tem("DESC")
                        lblSizeValue.Te xt = ds.Tables("Prod uct").Rows(0).I tem("ASIZE")
                        lblWHQty.Text = ds.Tables("Prod uct").Rows(0).I tem("OHQTY")

                        lblWHHead.Visib le = True
                        lblWHQty.Visibl e = True

                        ' if the requestor is at a store PC, then...
                        Dim vlVisitor As New ABCNetDepartmen tMenu(Request.S erverVariables( "remote_add r"))
                        If vlVisitor.IsSto re Then
                        Dim cmdStore As New OdbcCommand("SE LECT STORE_NO, PCODE, END_QTY " & _
                        "FROM ABCPROD.SIRBALP " & _
                        "WHERE STORE_NO = " & vlVisitor.Store Number & _
                        " AND PCODE = " & txtPCode.Text, conn)
                        Dim daStore As New OdbcDataAdapter (cmdStore)
                        conn.Open()
                        Dim dr As OdbcDataReader = cmdStore.Execut eReader

                        lblStoreQty.Tex t = 0
                        While dr.Read
                        lblStoreQty.Tex t = dr.Item("END_QT Y")
                        End While

                        daStore.Dispose ()
                        cmdStore.Dispos e()
                        conn.Dispose()

                        lblStoreHead.Vi sible = True
                        lblStoreQty.Vis ible = True
                        End If
                        vlVisitor.Dispo se()

                        dlProductNumber s.DataSource = ds.Tables(0)
                        dlProductNumber s.DataBind()

                        ds.Dispose()
                        da.Dispose()
                        cmd.Dispose()
                        conn.Dispose()

                        ' 03/16/05 WNS Added PriceIt
                        With btnPriceIt
                        .Visible = True
                        .Attributes.Add ("onclick", "NewWindow('Pri ceIt.aspx?pcode =" & txtPCode.Text & "','PriceLookUp ',350,350,0,'ce nter');")
                        End With

                        '6/29/07 Clear textbox
                        txtPCode.Text = ""
                        SetFocus(txtPCo de.ClientID)
                        End Sub

                        '07/20/07 This procedure sets focus to specific controls.
                        Private Sub SetFocus(ByVal ClientID As String)
                        Dim Script As New System.Text.Str ingBuilder
                        'Dim ClientID As String = FocusControl.Cl ientID
                        With Script
                        .Append("<scrip t language='javas cript'>")
                        .Append("docume nt.getElementBy Id('")
                        .Append(ClientI D)
                        .Append("').foc us();")
                        .Append("</script>")
                        End With
                        RegisterStartup Script("setFocu s", Script.ToString ())
                        End Sub
                        End Namespace
                        [/CODE]

                        Thanks

                        Comment

                        • Frinavale
                          Recognized Expert Expert
                          • Oct 2006
                          • 9749

                          #13
                          Originally posted by erickme
                          I'm tired of looking for the problem. I didn't create the code, it was the guy before me so maybe he have something that it's not allowing this to work. Here is the code if anyone can figured it out.
                          I remember having a similar problem to you in the past.
                          From what I remember, the problem was that the RegisterStartup Script method puts the JavaScript code in the <Body> portion of the Html. In order for the body to call your JavaScript function during the page's onload event, the JavaScript must exist in the <head> section of your Html.

                          What I to solve this solution was to put my JavaScript into an external JavaScript file hard code the import into the <head> section of my Html.

                          You don't need to put the JavaScript into an external file, but I'm almost certain that the JavaScript has to be defined in the <head> section in order to make the JavaScript call during your page's onload event.

                          eg:
                          [code=html]


                          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
                          <HTML>
                          <HEAD>
                          <title>My Page's Title</title>
                          <meta content="Micros oft Visual Studio .NET 7.1" name="GENERATOR ">
                          <meta content="Visual Basic .NET 7.1" name="CODE_LANG UAGE">
                          <meta content="VBScri pt" name="vs_defaul tClientScript">
                          <meta content="http://schemas.microso ft.com/intellisense/ie5" name="vs_target Schema">
                          <LINK href="Styles.cs s" type="text/css" rel="stylesheet ">
                          <script type="text/javascript">
                          onload = function()
                          {
                          document.getEle mentById('myTex tbox').focus();
                          }
                          </script>

                          </HEAD>
                          [/code]


                          Have you tried hard coding the JavaScript into the <head> section to see if this works?

                          -Frinny

                          Comment

                          • erickme
                            New Member
                            • Jul 2007
                            • 8

                            #14
                            I have tried that, don't work for me. This is how my script section on the page looks.

                            Code:
                            			<script language="javascript">
                            
                            				var win=null;
                            
                            				function NewWindow(mypage,myname,w,h,scroll,pos)
                            				{
                            					if(win!=null && win.open) win.close()
                            					
                            					if(pos=="random")
                            					{
                            						LeftPosition=(screen.width)?Math.floor(Math.random()*(screen.width-w)):100;
                            						TopPosition=(screen.height)?Math.floor(Math.random()*((screen.height-h)-75)):100;
                            					}
                            					
                            					if(pos=="center")
                            					{
                            						LeftPosition=(screen.width)?(screen.width-w)/2:100;
                            						TopPosition=(screen.height)?(screen.height-h)/2:100;
                            					}
                            					else if((pos!="center" && pos!="random") || pos==null)
                            					{
                            						LeftPosition=0;TopPosition=20;
                            					}
                            					
                            					settings='width='+w+',height='+h+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no';
                            					win=window.open(mypage,myname,settings);
                            					
                            					if(win.focus)
                            					{
                            						win.focus();
                            					}
                            				}
                            
                            				function CloseNewWin()
                            				{
                            					if(win!=null && win.open) win.close();
                            				}
                            				
                            				onload = function()
                            				{
                            					document.getElementById('txtPCode').focus();
                            				}
                            			</script>

                            Comment

                            • Frinavale
                              Recognized Expert Expert
                              • Oct 2006
                              • 9749

                              #15
                              Originally posted by erickme
                              I have tried that, don't work for me. This is how my script section on the page looks.
                              Are you getting an JavaScript errors on the page at all?
                              Like an "object expected" error or the like?

                              Comment

                              Working...