473,769 Members | 1,730 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.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
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(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
Jul 20 '07 #1
24 3923
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.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
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(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:
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( '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
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.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
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(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.

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.
mynothiddentext box.focus()

(Assuming one uses the NAME property, otherwise you'll need the getElementById( ))
Jul 25 '07 #10

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

Similar topics

2
5191
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 that previously had the focus (smartnavigation doesn't do the trick). Thanks, Marco
2
2435
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 postback occurs, no control has the focus. I would like it to be so that the control that causes the postback keeps the focus. Since I have 2 controls that potentally need to retain focus, using Javascript in this case is a PIA.
6
1388
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, except that after the postback, the page is shown reset -- scrolled to the top and with no control having focus. Can I maintain scroll/focus w/o writing client-side scripting? thanks
3
1647
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. Somebody know how to make this? Dexter
1
1180
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, so the 1st page takes back the focus instead of remaining behind the 2nd page. Even if the 2nd page takes time to render, the 1st page waits for its
5
2040
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 information and one that resets the form... The second on, the reset button, i would like to set focus back to the first textbox on the form. I already have an onload in my body, which sets the
2
3882
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 field. Form uses the Page_LoadComplete in order to access the last employeeID # in a dataview which is populated by an sqlDataObject querying an SQL Server dbs.
0
1787
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 hit the spacebar, but the little selection box does not appear around the first item like it does when you tab to a radiobutton list. So in essence, the user has no idea where they are on the screen. I've tried both the focus() method and...
8
6904
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" key how can I set the focus to the next box after the postback? Please help! Using Visual Studio 2005 Pro, Asp.net 2.0, vb.net, WinXP
0
9589
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9994
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9863
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8870
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7408
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6673
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3561
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.