 |
|
 |
This works great for postback. Can this code be modified so that it always retains focus whenever a page refresh (F5) is done? If so, how?
Thanks
modified 12 Mar '12.
|
|
|
|
 |
|
 |
Private Const SCRIPT_DOFOCUS As String = "window.setTimeout('DoFocus()', 1);" & vbCr & vbLf & " function DoFocus()" & vbCr & vbLf & " {" & vbCr & vbLf & " try {" & vbCr & vbLf & " document.getElementById('REQUEST_LASTFOCUS').focus();" & vbCr & vbLf & " } catch (ex) {}" & vbCr & vbLf & " }"
Protected Overrides Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
if not IsPostBack then
ClientName.Attributes.Add("onfocus", "try{document.getElementByID('__LASTFOCUS').value=this.id} catch(e) {}")
End if
ScriptManager.RegisterStartupScript(Me, Me.GetType(),
"ScriptDoFocus",
SCRIPT_DOFOCUS.Replace("REQUEST_LASTFOCUS", Request("__LASTFOCUS")),
True)
End sub
I am trying to use the above in a user control that has UpdatePanel.
I would like add this only to one Textbox.
After the postback my Textbox doesn't seem like getting the focus.
Am I missing some thing here?
Thanks for the help in advance.
L
|
|
|
|
 |
|
 |
Works like a charm and is a solution to a problem that Microsoft should have solved in the beginning... Very nice work George!
|
|
|
|
 |
|
 |
Hi there,
I was trying to use your solution in my application.It works perfect for other pages but its not working in a user control page where i am using a repeater control to retrieve data from database.
Behaviour: What exactly happens is when i click in first textbox and change value and then tab, the focus is lost.But if i repeat the steps the focus jumps to next field which is what i want. I have been cracking my head on this but not able to understand why it does not work with first post back .
any help will be really appreciated !!
Thanks
jashan
|
|
|
|
 |
|
 |
Move our call of Hook to LoadComplete
protected void Page_LoadComplete(object sender, EventArgs e)
{
if (!IsPostBack)
HookOnFocus(this.Page as Control);
And also change this part of code
private const string SCRIPT_DOFOCUS =
@"window.setTimeout('DoFocus()', 100); // More time!
function DoFocus()
{
try {
document.getElementById('REQUEST_LASTFOCUS').focus();
document.getElementById('REQUEST_LASTFOCUS').select(); // Select the all text in TextBox
} catch (ex) {}
}";
It's work of me in GridView using only Template Field (Textboxes)
Alexsander "Axia" Antunes
|
|
|
|
 |
|
 |
Can't you nowadays just add the following to the top of the aspx file?
MaintainScrollPositionOnPostback="true"
|
|
|
|
 |
|
 |
It's work for me
|
|
|
|
 |
|
 |
Just tried this out with a site using master pages and it is worthy to note I had to add this code to the page being displayed, not the Master page, for it to work in this context.
Thanks!
|
|
|
|
 |
|
 |
Example when it fails:
1. Focus is on a button in a DataList footer. The button is used for adding new rows and has id="mDataList_ctl03_mAddButton".
2. When pressing the button, a postback is done and a new row is added to the DataList.
3. Now, javascript cannot find the button because the id has been changed to "mDataList_ctl04_mAddButton".
Generally there is a problem when the id of the control is changed.
Any tips on how to solve this?
|
|
|
|
 |
|
 |
I was getting loads of this is not an object errors after async. Changing .value to .Value (note the upper first letter) in the HookOnFocus method fixed the problem for me.
Apart from that this is great!
|
|
|
|
 |
|
 |
Can you explain how to get this working with span (ASP.NET RadiobuttonLists)?!
Thnx!
|
|
|
|
 |
|
 |
Hi!, Grate article!!
This code not found for me:
Page.ClientScript.RegisterStartupScript(
typeof(MyPage),
"ScriptDoFocus",
SCRIPT_DOFOCUS.Replace("REQUEST_LASTFOCUS",
Request["__LASTFOCUS"]),
true);
This yes:
Page.ClientScript.RegisterStartupScript(
Page.GetType(),
"ScriptDoFocus",
SCRIPT_DOFOCUS.Replace("REQUEST_LASTFOCUS",
Request["__LASTFOCUS"]),
true);
Thanks for the article, very usefull!!
|
|
|
|
 |
|
 |
Maybe you should replace mypage to the name of your class .
Grtz
JustMe
|
|
|
|
 |
|
 |
I have plenty of pages that sometimes use AJAX and sometimes do normal postbacks and I needed to handle that issue. I found that when using AJAX an extra header value is present, by checking that you can handle the 'either/or' of whether you are using AJAX or not. I set a global variable in my page class... bool bUsingAjax = false; and in Page_Load I set it... if (Request.Headers["x-microsoftajax"] != null) bUsingAjax = true; Then if you need to swap between ClientScript or ScriptManager you can do a simple if(){}else{} based on your boolean. This lets you handle either occurance just as easily. Just thought I'd share.
|
|
|
|
 |
|
 |
I create some dinamic controls i.e. textboxes using a repeater a nice way of adding this on per control maner is just to hook up the control to a prerender and add the javascript ( or call to the hook method) in there :
Ie.
protected void AddFocusScript_PreRender(object sender, EventArgs e)
{
(sender as WebControl).Attributes.Add(
"onfocus",
"try{document.getElementById('__LASTFOCUS').value=this.id} catch(e) {}");
// you may want to use the HookOnFocus(sender) in here if children are important
}
Then add to whatever control you need the event such as
<asp:TextBox Width="100%" ID="txtComments" runat="server" AutoPostBack="true" OnPreRender="AddFocusScript_PreRender"
you may do this also if you have many controls and you only care about a few. (avoiding recursive method)
Not sure if it will add it multiple times though ( i mean incremental )
Hope it helps someone, and thanks for the article.
modified on Monday, March 10, 2008 12:24 PM
|
|
|
|
 |
|
 |
Hi,
Nice article, but just wondering is this can help me in fixing my problem. My validation controls [inside updatepanel] doesn't get focus after error. Not sure what to do, but your article gave me some hope.
Regards,
Deep
|
|
|
|
 |
|
 |
Hello George, thank you for this great solution.
I have the same environment that the coverboy with master pages, but moreover the update panels are inside of user controls. When I run, with routines prepared to master pages the Request["__LASTFOCUS"] is null and the script don´t work. I added to the routines in master page, but, in HookOnFocus, don´t enter into "if (CurrentControl is TextBox) ...".
Can you help me with this situation ?
Thank you so much.
|
|
|
|
 |
|
 |
The method Page.ClientScript.RegisterStartupScript() worked only on intial Load when using it with Ajax - UpdatePanel. Any async postbacks(triggered from within an UpdatePanel) did not fired the registered javascript function.
It seems that the solution is using: System.Web.UI.ScriptManager.RegisterStartupScript() as below:
System.Web.UI.ScriptManager.RegisterStartupScript(this.UpdatePanel1,
this.GetType(),
"ScriptDoFocus",
SCRIPT_DOFOCUS.Replace("REQUEST_LASTFOCUS", Request["__LASTFOCUS"]),
true)
This is from a forum out there:
In order to register javascript during an Async postback, you need to use the Scriptmanager RegisterClientScriptBlock instead of the Page's. Please note that this is a static (shared) function that is referenced like a constant, and not through an actual instance of the ScriptManager.
Another issue was that there is no "__LASTFOCUS" filed in the Request, so it must be added in the .aspx file, manually.
<input type="hidden" name="__LASTFOCUS" id="__LASTFOCUS" value="" />
And to set the cursor at the end of a textbox, just add another line to the SCRIPT_DOFOCUS string.
private const string SCRIPT_DOFOCUS =
"window.setTimeout('DoFocus()', 1);" +
"function DoFocus()" +
"{" +
"try {" +
"document.getElementById('REQUEST_LASTFOCUS').focus();" +
"document.getElementById('REQUEST_LASTFOCUS').value = document.getElementById('REQUEST_LASTFOCUS').value" +
"} catch (ex) {}" +
"}";
(it works with textboxes; however did not tryied it with other controls; by adding document.getElementById('REQUEST_LASTFOCUS').select() will select the text inside. )
George ... great article.
modified on Wednesday, December 12, 2007 5:47:44 AM
|
|
|
|
 |
|
 |
I am using this code in my master page. The problem i am facing is that i have some pages in which ajax is implemented and there are some pages in which ajax is not implemented. So I don't know whether to use ScriptManager.RegisterStartupScript or Page.ClientScript.RegisterStartupScript.
If i use ScriptManager.RegisterStartupScript only ajax enabled pages work and if i use Page.ClientScript.RegisterStartupScript only pages without ajax work.Plz help me out.Thanx in advance.
|
|
|
|
 |
|
 |
with the deprecation of SmartNavigation, I'm looking for a workaround that will still allow me to "showModalDialog" and keep the postback in the same page - have you manged to do this? Note that replacing SmartNavigation with either the page directive or Page.MaintainScrollPositionOnPostBack just doesn't cut it, and yes I could do it via ajax but I'm stuck in this place at the moment.
John
|
|
|
|
 |
|
 |
I've the following piece of code in at class level, so i can access it anywhere in that class
private const string SCRIPT_DOFOCUS =
@"window.setTimeout('DoFocus()', 1);
function DoFocus()
{
try {
document.getElementById('REQUEST_LASTFOCUS').focus();
} catch (ex) {}
}";
This follwoing code is being used in checkbox event "chkVehiclesOwned", what i am doing here is that im keeping the focus on the same checkbox after it postbacks but i don't know why ain't it working. the same code is working fine in other checkbox events. Notice one thing that the client id i've used in the script it something like "ctl00_ContentPlaceHolder1_chkVehiclesOwned" this is because the checkbox gets new id in master pages n the above id has to be used to get your work done. Dude for last few days im stuck into it n i dont know what to do :S please help. Thanks
if (chkVehiclesOwned.Checked == true)
{
txtVehiclesOwned.Enabled = true;
}
else
{
txtVehiclesOwned.Enabled = false;
}
ScriptManager.RegisterStartupScript(this, typeof(Survey), "DoFocus", SCRIPT_DOFOCUS.Replace("REQUEST_LASTFOCUS", "ctl00_ContentPlaceHolder1_chkVehiclesOwned"), true);
|
|
|
|
 |
|
 |
First off, thanks for the nice example.
I am currently working on a web application which uses Anthem.net rather than AJAX (this project was started by someone else before MS AJAX/Atlas were available - unfortunately).
I have a number of dropdownlist, radiobuttonlist etc. controls which perform automatic callbacks. Setting focus in ASP.NET 2.0 on page load is easy enough, but for the purpose of enabling a user to use only their keyboard to fill out a large form, maintaining focus between call- or postbacks is essential.
When a page first loads in IE6, selecting a value using either mouse or keyboard from a dropdownlist causes IE to lose focus. Subsequent selects from the same list, however, and the focus stays intact. Whoever thought that up deserves to be beaten with a stick (you can tell this really annoys me).
Anyway, so your nice example solved that, and I thought I was in the clear. In Firefox, however, when you select something using the keyboard, the actual call- or postback only happens after the control loses focus. So when i select something, as soon as I press tab the callback happens, and focus is set to the control that I just tabbed away from. In other words, focus is always one behind the control that should be focused.
Now I know this is not a flaw in your code, but rather YET ANOTHER horrible browser inconsistency. I wonder if anyone can suggest a workaround?
Another thing i'd like to point out:
ASP controls such as radiobuttonlists, checkboxlists unfortunately do not render attributes for each of their containing controls. So although something like RadioButtonList.Atrributes.Add("onfocus" .... will not generate any errors, the resulting radio buttons on the page will not have this attribute set. This is a known issue - the only way around it is to override each of these control's render methods.
Any comments welcome
|
|
|
|
 |
|
 |
Hi,
the Problem is apparently that the onfocus event of the next control will not be called prior to postback. IE and FireFox have not exactly the same behaviour regarding events. Please check exactly which event calls the postback in Anthem.net framework using FireFox (in can be that because of some technical issue initiating of Postback in IE and FireFox are bound to different events). After you have it we can think about a workaround.
|
|
|
|
 |
|
 |
Hello,
I had a quick look - it seems Anthem fires the callback on the onchange or onclick events depending on the type of input. Keep in mind that when using the mouse the behaviour is the same in both IE/FF, eg: for a dropdownlist the postback occurs as soon as the selectedindex changes. When using the keyboard IE calls the postback on every change of the selectedindex, FF only when the control loses focus.
|
|
|
|
 |
|
 |
Hi,
How can maintain focus for dynamic created user controls?
regards
Christian
|
|
|
|
 |