I have a page setup like so:
<ajax:UpdatePanel id="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox id="TextBox1" runat="server" AutoPostBack="true"/>
<asp:TextBox id="TextBox2" runat="server" AutoPostBack="true"/>
</ContentTemplate>
</ajax:UpdatePanel>
<asp:TextBox id="TextBox3" runat="server"/>
Whenever there is a change within TextBox1 or TextBox2 an async postback takes place. This is of course initiated by moving the focus to a different control after changing the text. The problem is when the async postback completes the control who gained focus loses that focus. It doesn’t matter whether it is inside the update panel or out.
I’ve tried adding javascript to the masterpage:
<script type="text/javascript">
var lastFocused = null;
$(document).ready(function() {
$('input').focus(function() {
lastFocused = this;
});
$('.dropdown').focus(function() {
lastFocused = this;
});
});
function RestoreFocus(source, args) {
if (lastFocused != null)
lastFocused.focus();
}
function AddRequestHandler() {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(RestoreFocus);
}
</script>
Along with
<body onload="AddRequestHandler">
I know lastFocused is getting a value and RestoreFocus is running, but whenever it runs the value of lastFocused is null.
Does anybody have a fix for either my javascript or a solution to the problem in general?
There are a few problems here, easily solved! Since these elements get replaced, the
.focus()handlers won’t stick, you’ll need.live(), like this:Note: you’ll need jQuery 1.4.1+ to support the
focusevent with.live()Also you should use
add_endRequestonce, like this:endRequestfires when an aync-postback completes, rather than only on the initial page load.