views:

21

answers:

1

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?

A: 

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:

var lastFocused = null;
$(function() {
  $('input, .dropdown').live('focus', function() {
    lastFocused = this;
  });
});

Note: you'll need jQuery 1.4.1+ to support the focus event with .live()

Also you should use add_endRequest once, like this:

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(RestoreFocus);

endRequest fires when an aync-postback completes, rather than only on the initial page load.

Nick Craver
This does seem to work, although I've also had to change the RestoreFocus to search for the control based on id. I suspect, due to the controls in the update panel being brand new?
Mike Cellini