473,507 Members | 2,545 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Set Focus on PostBack

8 New Member
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.setFocus() that will do it. Nop this is .Net Framework 1.1 and textbox.setFocus() didn't exist back then. So I did the other simple thing add a javascript on body onload="document.getElementById(<%= txtPCode.ClientID %>).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
Expand|Select|Wrap|Line Numbers
  1.  
  2.         Private Sub SetFocus(ByVal ClientID As String)
  3.             Dim Script As New System.Text.StringBuilder
  4.             'Dim ClientID As String = FocusControl.ClientID
  5.             With Script
  6.                 .Append("<script language='javascript'>")
  7.                 .Append("document.getElementById('")
  8.                 .Append(ClientID)
  9.                 .Append("').focus();")
  10.                 .Append("</script>")
  11.             End With
  12.             RegisterStartupScript("setFocus", Script.ToString())
  13.         End Sub
  14.  
and calling it in from the Page_Load like this SetFocus(textbox.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
Jul 20 '07 #1
24 3882
Frinavale
9,735 Recognized Expert Moderator Expert
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.setFocus() that will do it. Nop this is .Net Framework 1.1 and textbox.setFocus() didn't exist back then. So I did the other simple thing add a javascript on body onload="document.getElementById(<%= txtPCode.ClientID %>).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
Expand|Select|Wrap|Line Numbers
  1.  
  2.         Private Sub SetFocus(ByVal ClientID As String)
  3.             Dim Script As New System.Text.StringBuilder
  4.             'Dim ClientID As String = FocusControl.ClientID
  5.             With Script
  6.                 .Append("<script language='javascript'>")
  7.                 .Append("document.getElementById('")
  8.                 .Append(ClientID)
  9.                 .Append("').focus();")
  10.                 .Append("</script>")
  11.             End With
  12.             RegisterStartupScript("setFocus", Script.ToString())
  13.         End Sub
  14.  
and calling it in from the Page_Load like this SetFocus(textbox.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:
Expand|Select|Wrap|Line Numbers
  1. <script language=javascript type="text/javascript">
  2. onload = function()
  3. {            /*get all input elements on page */
  4.                 var allinputelements=document.getElementsByTagName('input');
  5.                 var len= A.length;    
  6.                 /* setting the focus to the first input element that allows focus*/ 
  7.  
  8.               for(var i = 0; i < len; i++)
  9.               {
  10.                   try{
  11.                         allinputelements[i].focus(); 
  12.                         break;
  13.                    }
  14.                    catch(error)
  15.                    {/*focus wasn't set*/}
  16.                 }
  17.  
  18. }
  19. </script>
  20.  
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('nameOfYourControlStoredInTheHidden FieldYouRegistered').

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
Jul 20 '07 #2
nateraaaa
663 Recognized Expert Contributor
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.setFocus() that will do it. Nop this is .Net Framework 1.1 and textbox.setFocus() didn't exist back then. So I did the other simple thing add a javascript on body onload="document.getElementById(<%= txtPCode.ClientID %>).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
Expand|Select|Wrap|Line Numbers
  1.  
  2.         Private Sub SetFocus(ByVal ClientID As String)
  3.             Dim Script As New System.Text.StringBuilder
  4.             'Dim ClientID As String = FocusControl.ClientID
  5.             With Script
  6.                 .Append("<script language='javascript'>")
  7.                 .Append("document.getElementById('")
  8.                 .Append(ClientID)
  9.                 .Append("').focus();")
  10.                 .Append("</script>")
  11.             End With
  12.             RegisterStartupScript("setFocus", Script.ToString())
  13.         End Sub
  14.  
and calling it in from the Page_Load like this SetFocus(textbox.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.

Expand|Select|Wrap|Line Numbers
  1. Page.RegisterStartupScript("SetFocus", ("<script>document.getElementById('" + (txtfirstName.ClientID + "').focus();</script>")))
Nathan
Jul 20 '07 #3
erickme
8 New Member
Thanks, but neither worked.

I don't know what else to try.
Jul 25 '07 #4
Frinavale
9,735 Recognized Expert Moderator Expert
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
Jul 25 '07 #5
Plater
7,872 Recognized Expert Expert
You could try viewing the source on say a google page and seeing what they do?
Jul 25 '07 #6
Frinavale
9,735 Recognized Expert Moderator Expert
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:
Expand|Select|Wrap|Line Numbers
  1. <script language=javascript type="text/javascript">
  2.       onload = function()
  3.       {            /*get all input elements on page */
  4.                       var allinputelements=document.getElementsByTagName('in  put');
  5.                       var len= allinputelements.length; 
  6.                       /* setting the focus to the first input element that allows focus*/
  7.                     for(var i = 0; i < len; i++)
  8.                     {
  9.                         try{
  10.                               allinputelements[i].focus();
  11.                               break;
  12.                          }
  13.                          catch(error)
  14.                          {/*focus wasn't set*/}
  15.  
  16.                       }
  17.       }
  18. </script>
  19.  
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
Jul 25 '07 #7
Plater
7,872 Recognized Expert Expert
I am a little confused. Do all the html elements not still have the .focus() in javascript?
Expand|Select|Wrap|Line Numbers
  1. <body onload="myobj.focus()">
  2.  
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
Jul 25 '07 #8
Frinavale
9,735 Recognized Expert Moderator Expert
I am a little confused. Do all the html elements not still have the .focus() in javascript?
Expand|Select|Wrap|Line Numbers
  1. <body onload="myobj.focus()">
  2.  
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).
Jul 25 '07 #9
Plater
7,872 Recognized Expert Expert
Why all this talk of hidden textboxes?
He knows the name of the textbox.
It's not hidden.
mynothiddentextbox.focus()

(Assuming one uses the NAME property, otherwise you'll need the getElementById())
Jul 25 '07 #10
Frinavale
9,735 Recognized Expert Moderator Expert
Why all this talk of hidden textboxes?
He knows the name of the textbox.
It's not hidden.
mynothiddentextbox.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?
Jul 25 '07 #11
erickme
8 New Member
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.

Expand|Select|Wrap|Line Numbers
  1. Imports System.Data.Odbc
  2.  
  3. Namespace ASPNET.StarterKit.Portal
  4.  
  5.     Public Class ProductLookUpPage
  6.         'Inherits System.Web.UI.Page
  7.         Inherits ASPNET.StarterKit.Portal.PortalPage
  8.         Protected WithEvents lnkReturn0 As System.Web.UI.WebControls.LinkButton
  9.         Protected WithEvents lnkReturn1 As System.Web.UI.WebControls.LinkButton
  10.  
  11.         Protected WithEvents phBanner As System.Web.UI.WebControls.PlaceHolder
  12.         Protected WithEvents lblTitle As System.Web.UI.WebControls.Label
  13.         Protected WithEvents cmdLocate As System.Web.UI.WebControls.Button
  14.         Protected WithEvents txtPCode As System.Web.UI.WebControls.TextBox
  15.         Protected WithEvents vsPCode As System.Web.UI.WebControls.ValidationSummary
  16.         Protected WithEvents rfvPCode As System.Web.UI.WebControls.RequiredFieldValidator
  17.         Protected WithEvents revPCode As System.Web.UI.WebControls.RegularExpressionValidator
  18.         Protected WithEvents cvPCode As System.Web.UI.WebControls.CustomValidator
  19.         Protected WithEvents dlProductNumbers As System.Web.UI.WebControls.DataList
  20.         Protected WithEvents lblPCodeValue As System.Web.UI.WebControls.Label
  21.         Protected WithEvents lblDescValue As System.Web.UI.WebControls.Label
  22.         Protected WithEvents lblSizeValue As System.Web.UI.WebControls.Label
  23.         Protected WithEvents lblWHHead As System.Web.UI.WebControls.Label
  24.         Protected WithEvents lblWHQty As System.Web.UI.WebControls.Label
  25.         Protected WithEvents lblStoreHead As System.Web.UI.WebControls.Label
  26.         Protected WithEvents lblStoreQty As System.Web.UI.WebControls.Label
  27.         Protected WithEvents btnPriceIt As System.Web.UI.HtmlControls.HtmlInputButton
  28.         Protected WithEvents spnContent As System.Web.UI.HtmlControls.HtmlGenericControl
  29.  
  30. #Region " Web Form Designer Generated Code "
  31.  
  32.         'This call is required by the Web Form Designer.
  33.         <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
  34.  
  35.         End Sub
  36.  
  37.         Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
  38.             'CODEGEN: This method call is required by the Web Form Designer
  39.             'Do not modify it using the code editor.
  40.             InitializeComponent()
  41.         End Sub
  42.  
  43. #End Region
  44.  
  45.         Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  46.             Trace.Warn("Default.aspx.vb", "Called Page_Load()")
  47.             'DO NOT remove this line
  48.             'This is what loads the banner into the top
  49.             phBanner.Controls.Add(Page.LoadControl("../../../DesktopPortalBanner.ascx"))
  50.  
  51.             '07/20/07
  52.             SetFocus(txtPCode.ClientID)
  53.  
  54.             'Counteract the DHTML onclick event assigned to the Look-Up Command Button
  55.             txtPCode.Attributes.Add("onfocus", "document.forms(0).cmdLookup.disabled = false;")
  56.  
  57.             ' 03/16/05 WNS Added PriceIt
  58.             btnPriceIt.Visible = False
  59.             Page.RegisterHiddenField("__EVENTTARGET", cmdLocate.ClientID)
  60.             If Page.IsPostBack = False Then
  61.                 '  Store URL Referrer to return to portal
  62.                 Try
  63.                     ViewState("UrlReferrer") = Request.UrlReferrer.ToString()
  64.                 Catch ex As Exception
  65.                     Dim clsApp As New CustomAppSettings
  66.                     ViewState("UrlReferrer") = clsApp.GetAppSetting("StoreTab_Url")
  67.                 End Try
  68.  
  69.                 Page.RegisterHiddenField("__EVENTTARGET", cmdLocate.ClientID)
  70.  
  71.                 If Request.Params("pcode") <> "" Then
  72.                     Dim clsProducts As New ABCProducts
  73.                     If clsProducts.IsValidPCode(Request.Params("pcode")) Then
  74.                         txtPCode.Text = Request.Params("pcode")
  75.                         LocateProduct()
  76.                     End If
  77.                 End If
  78.  
  79.             End If
  80.             RegisterStartupScript("SetFocus", ("<script>document.getElementById('txtPCode').focus();</script>"))
  81.  
  82.         End Sub
  83.  
  84.         'DO NOT remove this return procedure
  85.         Private Sub lnkReturn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lnkReturn0.Click, lnkReturn1.Click
  86.             'Return to Portal
  87.             Response.Redirect(CType(ViewState("UrlReferrer"), String))
  88.         End Sub
  89.  
  90.         Private Sub cmdLocate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLocate.Click
  91.             'A PCode has been entered and the submit button clicked
  92.  
  93.             'Query the SIRBALP by PCode and load into DataSet
  94.             If Page.IsValid Then
  95.                 LocateProduct()
  96.             End If
  97.  
  98.         End Sub
  99.  
  100.         Public Sub ValidatePCode(ByVal sender As Object, ByVal e As ServerValidateEventArgs)
  101.             Try
  102.                 Dim intTest As Integer = txtPCode.Text
  103.             Catch ex As Exception
  104.                 e.IsValid = False
  105.                 Exit Sub
  106.             End Try
  107.  
  108.             'July 11, 2007
  109.             'Validates PCODE against AS400 to see if is valid
  110.             Dim sqlCmd As String = "SELECT * FROM ABCPROD.INVMSTP WHERE (PCODE = " & txtPCode.Text & ") "
  111.             Dim conn As New OdbcConnection(System.Configuration.ConfigurationSettings.AppSettings("AS400"))
  112.             Dim cmd As New OdbcCommand(sqlCmd, conn)
  113.             conn.Open()
  114.             Dim AS400reader As OdbcDataReader = cmd.ExecuteReader
  115.  
  116.             AS400reader.Read()
  117.  
  118.             If AS400reader.HasRows Then
  119.                 e.IsValid = True
  120.             Else
  121.                 e.IsValid = False
  122.             End If
  123.         End Sub
  124.  
  125.         Private Sub LocateProduct()
  126.             txtPCode.Text.Trim()
  127.  
  128.             Dim sqlCmd As String = "SELECT STORE_NO, PCODE, END_QTY, S#STAT " & _
  129.                     "FROM ABCPROD.SIRBALP, ABCPROD.STRMSTP " & _
  130.                     "WHERE ((ABCPROD.SIRBALP.STORE_NO = ABCPROD.STRMSTP.STRNO) " & _
  131.                     "AND (S#STAT = 'A')) " & _
  132.                     "AND (PCODE = " & txtPCode.Text & ") " & _
  133.                     "AND (STORE_NO <> 10) " & _
  134.                     "AND (STORE_NO <> 11) " & _
  135.                     "AND (STORE_NO < 219) " & _
  136.                     "AND (END_QTY > 0) " & _
  137.                     "ORDER BY STORE_NO, PCODE, END_QTY"
  138.  
  139.             Dim conn As New OdbcConnection(System.Configuration.ConfigurationSettings.AppSettings("AS400"))
  140.             Dim cmd As New OdbcCommand(sqlCmd, conn)
  141.             cmd.CommandType = CommandType.Text
  142.             Dim da As New OdbcDataAdapter(cmd)
  143.             Dim ds As New DataSet
  144.             da.Fill(ds)
  145.  
  146.             cmd.CommandText = "SELECT PCODE, ASIZE, DESC, OHQTY " & _
  147.                 "FROM ABCPROD.INVMSTP " & _
  148.                 "WHERE (PCODE = " & txtPCode.Text & ") "
  149.             da.SelectCommand = cmd
  150.             da.Fill(ds, "Product")
  151.  
  152.             lblPCodeValue.Text = ds.Tables("Product").Rows(0).Item("PCODE")
  153.             lblDescValue.Text = ds.Tables("Product").Rows(0).Item("DESC")
  154.             lblSizeValue.Text = ds.Tables("Product").Rows(0).Item("ASIZE")
  155.             lblWHQty.Text = ds.Tables("Product").Rows(0).Item("OHQTY")
  156.  
  157.             lblWHHead.Visible = True
  158.             lblWHQty.Visible = True
  159.  
  160.             ' if the requestor is at a store PC, then...
  161.             Dim vlVisitor As New ABCNetDepartmentMenu(Request.ServerVariables("remote_addr"))
  162.             If vlVisitor.IsStore Then
  163.                 Dim cmdStore As New OdbcCommand("SELECT STORE_NO, PCODE, END_QTY " & _
  164.                     "FROM ABCPROD.SIRBALP " & _
  165.                     "WHERE STORE_NO = " & vlVisitor.StoreNumber & _
  166.                     " AND PCODE = " & txtPCode.Text, conn)
  167.                 Dim daStore As New OdbcDataAdapter(cmdStore)
  168.                 conn.Open()
  169.                 Dim dr As OdbcDataReader = cmdStore.ExecuteReader
  170.  
  171.                 lblStoreQty.Text = 0
  172.                 While dr.Read
  173.                     lblStoreQty.Text = dr.Item("END_QTY")
  174.                 End While
  175.  
  176.                 daStore.Dispose()
  177.                 cmdStore.Dispose()
  178.                 conn.Dispose()
  179.  
  180.                 lblStoreHead.Visible = True
  181.                 lblStoreQty.Visible = True
  182.             End If
  183.             vlVisitor.Dispose()
  184.  
  185.             dlProductNumbers.DataSource = ds.Tables(0)
  186.             dlProductNumbers.DataBind()
  187.  
  188.             ds.Dispose()
  189.             da.Dispose()
  190.             cmd.Dispose()
  191.             conn.Dispose()
  192.  
  193.             ' 03/16/05 WNS Added PriceIt
  194.             With btnPriceIt
  195.                 .Visible = True
  196.                 .Attributes.Add("onclick", "NewWindow('PriceIt.aspx?pcode=" & txtPCode.Text & "','PriceLookUp',350,350,0,'center');")
  197.             End With
  198.  
  199.             '6/29/07 Clear textbox
  200.             txtPCode.Text = ""
  201.             SetFocus(txtPCode.ClientID)
  202.         End Sub
  203.  
  204.         '07/20/07 This procedure sets focus to specific controls.
  205.         Private Sub SetFocus(ByVal ClientID As String)
  206.             Dim Script As New System.Text.StringBuilder
  207.             'Dim ClientID As String = FocusControl.ClientID
  208.             With Script
  209.                 .Append("<script language='javascript'>")
  210.                 .Append("document.getElementById('")
  211.                 .Append(ClientID)
  212.                 .Append("').focus();")
  213.                 .Append("</script>")
  214.             End With
  215.             RegisterStartupScript("setFocus", Script.ToString())
  216.         End Sub
  217. End Namespace
  218.  
Thanks
Jul 27 '07 #12
Frinavale
9,735 Recognized Expert Moderator Expert
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 RegisterStartupScript 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:
Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  4. <HTML>
  5.     <HEAD>
  6.         <title>My Page's Title</title>
  7.         <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
  8.         <meta content="Visual Basic .NET 7.1" name="CODE_LANGUAGE">
  9.         <meta content="VBScript" name="vs_defaultClientScript">
  10.         <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
  11.         <LINK href="Styles.css" type="text/css" rel="stylesheet">    
  12.            <script type="text/javascript">
  13.                onload = function()
  14.                { 
  15.                   document.getElementById('myTextbox').focus();
  16.                }
  17.            </script>
  18.  
  19.     </HEAD>
  20.  

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

-Frinny
Jul 27 '07 #13
erickme
8 New Member
I have tried that, don't work for me. This is how my script section on the page looks.

Expand|Select|Wrap|Line Numbers
  1.             <script language="javascript">
  2.  
  3.                 var win=null;
  4.  
  5.                 function NewWindow(mypage,myname,w,h,scroll,pos)
  6.                 {
  7.                     if(win!=null && win.open) win.close()
  8.  
  9.                     if(pos=="random")
  10.                     {
  11.                         LeftPosition=(screen.width)?Math.floor(Math.random()*(screen.width-w)):100;
  12.                         TopPosition=(screen.height)?Math.floor(Math.random()*((screen.height-h)-75)):100;
  13.                     }
  14.  
  15.                     if(pos=="center")
  16.                     {
  17.                         LeftPosition=(screen.width)?(screen.width-w)/2:100;
  18.                         TopPosition=(screen.height)?(screen.height-h)/2:100;
  19.                     }
  20.                     else if((pos!="center" && pos!="random") || pos==null)
  21.                     {
  22.                         LeftPosition=0;TopPosition=20;
  23.                     }
  24.  
  25.                     settings='width='+w+',height='+h+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no';
  26.                     win=window.open(mypage,myname,settings);
  27.  
  28.                     if(win.focus)
  29.                     {
  30.                         win.focus();
  31.                     }
  32.                 }
  33.  
  34.                 function CloseNewWin()
  35.                 {
  36.                     if(win!=null && win.open) win.close();
  37.                 }
  38.  
  39.                 onload = function()
  40.                 {
  41.                     document.getElementById('txtPCode').focus();
  42.                 }
  43.             </script>
  44.  
Jul 27 '07 #14
Frinavale
9,735 Recognized Expert Moderator Expert
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?
Jul 27 '07 #15
Plater
7,872 Recognized Expert Expert
As much as I hate to admit it (:-P) if you run it in firefox with that DOM parser thing on you will see a lot more hidden errors.

Are you remembering to have your body tag's onload function call out to that javascript onload thing
Jul 27 '07 #16
Frinavale
9,735 Recognized Expert Moderator Expert
I'm going to ask one more small but vital question.

Are you using any use of Ajax in your html design?
Are you using the AjaxControlToolkit's UpdatePanel?
Jul 27 '07 #17
erickme
8 New Member
I just tried with firefox and it works, but not with Internet explorer. I didn't get any javascript error. I don't get it, whats wrong with IE (lol) then.

I'm not using AJAX in this application, this is an old application, it was develop long time before I started working here.
Jul 27 '07 #18
Frinavale
9,735 Recognized Expert Moderator Expert
I just tried with firefox and it works, but not with Internet explorer. I didn't get any javascript error. I don't get it, whats wrong with IE (lol) then.

I'm not using AJAX in this application, this is an old application, it was develop long time before I started working here.
Have you checked out w3c?
Have you seen their focus() method example?

I tried their example in IE and it works fine....
Maybe you might find then answer in w3c.
Jul 27 '07 #19
erickme
8 New Member
Have you checked out w3c?
Have you seen their focus() method example?

I tried their example in IE and it works fine....
Maybe you might find then answer in w3c.
It doesn't seem to work with a asp button, I got this error:
Compiler Error Message: BC30390: 'ASPNET.StarterKit.Portal.ProductLookUpPage.Privat e Sub SetFocus(ClientID As String)' is not accessible in this context because it is 'Private'.
Jul 27 '07 #20
Frinavale
9,735 Recognized Expert Moderator Expert
It doesn't seem to work with a asp button, I got this error:
Compiler Error Message: BC30390: 'ASPNET.StarterKit.Portal.ProductLookUpPage.Privat e Sub SetFocus(ClientID As String)' is not accessible in this context because it is 'Private'.
Could you post the html code for your aspx page?
Jul 27 '07 #21
nateraaaa
663 Recognized Expert Contributor
It doesn't seem to work with a asp button, I got this error:
Compiler Error Message: BC30390: 'ASPNET.StarterKit.Portal.ProductLookUpPage.Privat e Sub SetFocus(ClientID As String)' is not accessible in this context because it is 'Private'.
'07/20/07 This procedure sets focus to specific controls.
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

Change the SetFocus method to be a public method instead of a private method.

Nathan
Jul 27 '07 #22
erickme
8 New Member
Here is the html

Expand|Select|Wrap|Line Numbers
  1.     <body bottomMargin="0" leftMargin="0" topMargin="0" rightMargin="0" marginwidth="0" marginheight="0">
  2.         <form runat="server">
  3.             <table cellSpacing="0" cellPadding="0" width="100%" border="0">
  4.                 <tr vAlign="top">
  5.                     <td colSpan="2"><asp:placeholder id="phBanner" runat="server"></asp:placeholder></td>
  6.                 </tr>
  7.                 <tr>
  8.                     <td class="contentCellTop" vAlign="top">
  9.                         <center><br>
  10.                             <table width="650" border="0">
  11.                                 <tr>
  12.                                     <td>
  13.                                         <TABLE id="Table1" cellSpacing="2" cellPadding="2" width="100%" border="0">
  14.                                             <TR>
  15.                                                 <TD>
  16.                                                     <asp:label id="lblTitle" runat="server" CssClass="Head"> Product Locate</asp:label></TD>
  17.                                                 <TD>
  18.                                                     <P align="right">[
  19.                                                         <asp:linkbutton id="lnkReturn0" CssClass="CommandButton" Visible="True" Runat="server" EnableViewState="True"
  20.                                                             Enabled="True" CausesValidation="False">return</asp:linkbutton>]</P>
  21.                                                 </TD>
  22.                                             </TR>
  23.                                         </TABLE>
  24.                                         <HR noShade SIZE="1">
  25.                                         <span class="normal" id="spnContent" runat="server">
  26.             <P>Enter a Product Code (PCode) or look it up using the look-up function provided.&nbsp; Once you select a product, 
  27.                                                 you can find a display of stores which have the product in stock as of&nbsp;end 
  28.                                                 of business&nbsp;yesterday.</P>
  29.             <P><asp:validationsummary id="vsPCode" runat="server" CssClass="Error" Width="100%" HeaderText="The following error(s) occurred:"></asp:validationsummary></P>
  30.             <P align="center"><asp:textbox id="txtPCode" runat="server" Width="63px" ToolTip="Enter the PCode into this textbox."></asp:textbox><asp:requiredfieldvalidator id="rfvPCode" runat="server" CssClass="strError" ToolTip="You must enter a valid PCode to continue."
  31.                                                     ControlToValidate="txtPCode" Display="Dynamic" ErrorMessage="You must enter a valid PCode to continue.">!</asp:requiredfieldvalidator><asp:regularexpressionvalidator id="revPCode" runat="server" CssClass="strError" ToolTip="The PCode can only contain 5 or 6 numbers."
  32.                                                     ControlToValidate="txtPCode" Display="Dynamic" ErrorMessage="The PCode can only contain 5 or 6 numbers." ValidationExpression="\d{5,6}">!</asp:regularexpressionvalidator><asp:customvalidator id="cvPCode" runat="server" CssClass="strError" ToolTip="The Product Code entered was not found."
  33.                                                     Display="Dynamic" ErrorMessage="The Product Code entered was not found." EnableClientScript="False" OnServerValidate="ValidatePCode">!</asp:customvalidator>&nbsp;
  34.                                                 <asp:button id="cmdLocate" runat="server" CssClass="CommandButton" ToolTip="Click here to locate the product."
  35.                                                     Text="Locate"></asp:button>&nbsp; <INPUT class="CommandButton" id="cmdLookup" onclick="this.disabled = true; NewWindow('product_lookup.aspx','ProductLookUp',550,500,0,'center');"
  36.                                                     type="button" value="Look-Up PCode" name="cmdLookup"></P>
  37.             <P align="center">
  38.                                                 <TABLE id="tblInfoContainment" cellSpacing="2" cellPadding="2" width="475" border="0">
  39.                                                     <TR>
  40.                                                         <TD vAlign="top">
  41.                                                             <TABLE id="tblResultsLabels" cellSpacing="3" cellPadding="3" border="0">
  42.                                                                 <TR>
  43.                                                                     <TD class="strNormal" colSpan="4">Click the LOCATE button to initiate the query.</TD>
  44.                                                                 </TR>
  45.                                                                 <TR class="Normal">
  46.                                                                     <TD>
  47.                                                                         <asp:label id="lblPCodeValue" runat="server" CssClass="strNormal"></asp:label></TD>
  48.                                                                     <TD colSpan="2">
  49.                                                                         <P align="left">
  50.                                                                             <asp:label id="lblDescValue" runat="server" CssClass="Normal"></asp:label></P>
  51.                                                                     </TD>
  52.                                                                     <TD>
  53.                                                                         <asp:label id="lblSizeValue" runat="server" CssClass="Normal"></asp:label></TD>
  54.                                                                 </TR>
  55.                                                                 <TR>
  56.                                                                     <TD colSpan="2">
  57.                                                                         <asp:Label id="lblWHHead" runat="server" CssClass="strNormal" Visible="False">Warehouse O/H:</asp:Label>&nbsp;
  58.                                                                         <asp:Label id="lblWHQty" runat="server" CssClass="Normal"></asp:Label></TD>
  59.                                                                     <TD colSpan="2">
  60.                                                                         <asp:Label id="lblStoreHead" runat="server" CssClass="strNormal" Visible="False">Your Store O/H:</asp:Label>&nbsp;
  61.                                                                         <asp:Label id="lblStoreQty" runat="server" CssClass="normal" Visible="False"></asp:Label>&nbsp;</TD>
  62.                                                                 </TR>
  63.                                                             </TABLE>
  64.                                                         </TD>
  65.                                                         <TD vAlign="bottom"><INPUT id="btnPriceIt" type="button" value="Price It!" name="btnPriceIt" runat="server"
  66.                                                                 class="CommandButton" tooltip="Click here to see the prices of the product in the different price zones">&nbsp;</TD>
  67.                                                     </TR>
  68.                                                 </TABLE>
  69.                                             </P>
  70.             <P align="center">
  71.                                             </P>
  72.             <P align="center"><asp:datalist id="dlProductNumbers" runat="server" CssClass="Normal" Width="100%" RepeatColumns="5"
  73.                                                     CellPadding="3" BorderColor="#DEBA84" BorderStyle="None" BackColor="#DEBA84"
  74.                                                     GridLines="Both" BorderWidth="1px" CellSpacing="2">
  75.                                                     <SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#738A9C"></SelectedItemStyle>
  76.                                                     <HeaderTemplate>
  77.                                                         <TABLE id="tblDataHeader" cellSpacing="0" cellPadding="3" width="100%" border="0">
  78.                                                             <TR>
  79.                                                                 <TD align="center" class="strNormal" style="color: #ffffff;">The Product has been 
  80.                                                                     found in the following Stores:</TD>
  81.                                                             </TR>
  82.                                                         </TABLE>
  83.                                                     </HeaderTemplate>
  84.                                                     <FooterStyle ForeColor="#8C4510" BackColor="#F7DFB5"></FooterStyle>
  85.                                                     <ItemStyle ForeColor="#8C4510" BackColor="#FFF7E7"></ItemStyle>
  86.                                                     <ItemTemplate>
  87.                                                         <table id="tblDataItem" border="0" cellpadding="3" cellspacing="0" width="100%">
  88.                                                             <TR>
  89.                                                                 <td align="left" class="strNormal"><a href='<%# "../store_info_lookup.aspx?storenumber=" & DataBinder.Eval(Container.DataItem, "STORE_NO")%>'>Store
  90.                                                                         <%# DataBinder.Eval(Container.DataItem, "STORE_NO")%>
  91.                                                                     </a>
  92.                                                                     <span class="Normal">(<%# DataBinder.Eval(Container.DataItem, "END_QTY")%>)</span>
  93.                                                             </TR>
  94.                                                         </table>
  95.                                                     </ItemTemplate>
  96.                                                     <HeaderStyle Font-Bold="True" ForeColor="#DEBA84" BackColor="#A55129"></HeaderStyle>
  97.                                                     <AlternatingItemTemplate>
  98.                                                         <table id="tblDataAltItem" border="0" cellpadding="3" cellspacing="0">
  99.                                                             <TR>
  100.                                                                 <td align="left" class="strNormal"><a href='<%# "../store_info_lookup.aspx?storenumber=" & DataBinder.Eval(Container.DataItem, "STORE_NO")%>'>Store
  101.                                                                         <%# DataBinder.Eval(Container.DataItem, "STORE_NO")%>
  102.                                                                     </a>
  103.                                                                     <span class="Normal">(<%# DataBinder.Eval(Container.DataItem, "END_QTY")%>)</span>
  104.                                                             </TR>
  105.                                                         </table>
  106.                                                     </AlternatingItemTemplate>
  107.                                                 </asp:datalist></P>
  108.             <P align="left"><STRONG><U>Tip</U>:</STRONG> Hold down the shift&nbsp;key when you click on a store number to open 
  109.                                                 the store information in a new window.</P>
  110.             <P>[<asp:linkbutton id="lnkReturn1" runat="server" cssclass="CommandButton" borderstyle="none" text="Return"
  111.                                                     causesvalidation="False">return</asp:linkbutton>]</span></P>
  112.                                         <P>&nbsp;</P>
  113.                                     </td>
  114.                                 </tr>
  115.                             </table>
  116.                         </center>
  117.                     </td>
  118.                 </tr>
  119.                 <tr>
  120.                     <td class="contentCellBottom">&nbsp;</td>
  121.                 </tr>
  122.                 <tr>
  123.                     <td class="FootBg" vAlign="middle" height="30">
  124.                         <div align="center"><span class="SiteLink"><font color="#eeeeee">Thank you for visiting 
  125.                                     ABCNet.</font></span></div>
  126.                     </td>
  127.                 </tr>
  128.             </table>
  129.         </form>
  130.     </body>
  131.  
Jul 27 '07 #23
erickme
8 New Member
'07/20/07 This procedure sets focus to specific controls.
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

Change the SetFocus method to be a public method instead of a private method.

Nathan
I set it to public but still gives me an error
Jul 27 '07 #24
Frinavale
9,735 Recognized Expert Moderator Expert
It doesn't seem to work with a asp button, I got this error:
Compiler Error Message: BC30390: 'ASPNET.StarterKit.Portal.ProductLookUpPage.Privat e Sub SetFocus(ClientID As String)' is not accessible in this context because it is 'Private'.
You are getting this error because your button has a runat=server.
So since it is an asp button, it is trying to call the server side code called SetFocus (except this function is private and so you get an error). It is not calling the JavaScript function called SetFocus as because it is an asp button and is calling the Server Side code.

In order to call JavaScript using an asp button you'd have to do something like the following in your in your server side code:

BTN_MyButton.Attributes.Add("OnMouseUP", "SetFocus('" + TXT_myTextBox.ClientID"');")

However, the asp button will cause a PostBack event.
Since this happens your focus will be lost when the page is redisplayed in the browser.

If you were following the example from the w3c site and substituted the <input type="button"> for <asp:Button>, the example will obviously not work for these reasons.

-Frinny
Jul 27 '07 #25

Sign in to post your reply or Sign up for a free account.

Similar topics

2
5179
by: Marco Liedekerken | last post by:
Hi, Is it possible to retrieve the control that had the focus when the page was posted back? Because the focus is lost when a postback occurs I want to manually set the focus to the control...
2
2415
by: Elliot M. Rodriguez | last post by:
Is it possible to change a control's focus at runtime? I'm sure you can.... I have a form with 2 textbox controls that cause postbacks. They are located in the middle of my form. When a...
6
1376
by: Mike | last post by:
I have a few textbox controls that have autopostback so that when they loose focus they update a label control that shows the count of characters in their respective text control. This works fine,...
3
1637
by: Dexter | last post by:
Hello All, I have a web control that when receive the focus, a postback is called, using getPostBackEventReference. But, when the PostBack is called, i want that the focus goes to the web control....
1
1175
by: psual | last post by:
Hi I have a page (1st page) with a button. this button opens a new page (2nd page) in full-screen mode. The problem is that the 2nd page is always loaded before the postback of the 1st page,...
5
2023
by: Finn Stampe Mikkelsen | last post by:
Hi How can i set a focus to a textbox in my codebehind page?? I have this WebForm, that takes information from a user and 2 buttons on the form. One that takes action on the entered...
2
3859
by: Rey | last post by:
Howdy all. Using visual web developer (VB) on xp pro box. My problem with with a web form that on accessing the calendar control causes a postback that moves the cursor back to the txtFirstName...
0
1769
by: BizEd | last post by:
I have a textbox that fires an autopostback when filled in. The next field after the textbox is a RadioButtonList which I set focus to. The radiobutton list does have focus and activates when you...
8
6888
by: Mel | last post by:
I have several text boxes and drop-down lists in an AJAX Update Panel. All user inputs have the Postback property set to True. After I type something in the first input entry and press the "Tab"...
0
7223
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7110
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7372
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
5623
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5041
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4702
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3179
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1540
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
758
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.