How to maintain the focus on same control after asynchronous postback?

17,355

Solution 1

Here is a slightly modified version of @Darshan's script which uses jQuery. I like his solution because this 1 script will work with all UpdatePanels so you don't have to write code specifically for each and every UpdatePanel.

My modifications are:

  • Uses jQuery
  • Performs null checks
  • Doesn't pollute global namespace
  • Edit: Tabbing works as expected with TextBoxes with autopostback.

/* Retain element focus after UpdatePanel postback
***************************************************/
jQuery(function ($) {
    var focusedElementId = "";
    var prm = Sys.WebForms.PageRequestManager.getInstance();

    prm.add_beginRequest(function (source, args) {
        var fe = document.activeElement;
        if (fe != null) {
            focusedElementId = fe.id;
        } else {
            focusedElementId = "";
        }
    });

    prm.add_endRequest(function (source, args) {
        if (focusedElementId != "") {
            $("#" + focusedElementId).focus();
        }
    });
});

Chosen.jQuery

This version will work with the Chosen jQuery plugin.

/* Retain element focus after UpdatePanel postback
***************************************************/
jQuery(function ($) {
    var focusedElementSelector = "";
    var prm = Sys.WebForms.PageRequestManager.getInstance();

    prm.add_beginRequest(function (source, args) {
        var fe = document.activeElement;
        focusedElementSelector = "";

        if (fe != null) {
            if (fe.id) {
                focusedElementSelector = "#" + fe.id;
            } else {
                // Handle Chosen Js Plugin
                var $chzn = $(fe).closest('.chosen-container[id]');
                if ($chzn.size() > 0) {
                    focusedElementSelector = '#' + $chzn.attr('id') + ' input[type=text]';
                }
            }
        }
    });

    prm.add_endRequest(function (source, args) {
        if (focusedElementSelector) {
            $(focusedElementSelector).focus();
        }
    });
});

Solution 2

http://www.codeproject.com/Tips/674414/Set-Focus-on-the-Same-Control-after-Postback-using

check this, this may help u to understand the concept

Solution 3

Ohh Ok The problem is that the ASP.NET Javascript methode "WebForm_AutoFocus(...)" is not execute after a partial page update, so you can't use the built in function SetFocus(clientID) in the codebhind class. My solution register two eventhandlers one for beginRequest and one for endRequest. In the event method "beginRequest" i save the client control id. In the endRequest method i use this value to set the focus, e.g.: CODE:-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="shipper.aspx.cs" Inherits="shipper" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Restore Focus after background postback</title>
    <script language="javascript">
      var postbackElement = null;
      function RestoreFocus(source, args)
      {
        document.getElementById(postbackElement.id).focus();
      }
      function SavePostbackElement(source, args)
      {
        postbackElement = args.get_postBackElement();
      }
      function AddRequestHandler()
      {
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        prm.add_endRequest(RestoreFocus);
        prm.add_beginRequest(SavePostbackElement);
      }
    </script>
</head>
<body onload="AddRequestHandler()">
    <form id="form1" runat="server">
    <asp:ScriptManager ID="sm" runat="server"></asp:ScriptManager>
    <div>
        <asp:UpdatePanel runat="server" ID="updPanel1">
          <ContentTemplate>
            <asp:Panel ID="panel1" runat="server">
                <asp:RadioButtonList ID="rbList" runat="server" AutoPostBack="true">
                  <asp:ListItem Text="Rb 1" Value="1"></asp:ListItem>
                  <asp:ListItem Text="Rb 2" Value="2"></asp:ListItem>
                  <asp:ListItem Text="Rb 3" Value="3"></asp:ListItem>
                  <asp:ListItem Text="Rb 4" Value="4"></asp:ListItem>
                  <asp:ListItem Text="Rb 5" Value="5"></asp:ListItem>
                </asp:RadioButtonList><br />
                <asp:DropDownList ID="ddSample" runat="server" AutoPostBack="true">
                  <asp:ListItem Text="Item 1" Value="1"></asp:ListItem>
                  <asp:ListItem Text="Item 2" Value="2"></asp:ListItem>
                  <asp:ListItem Text="Item 3" Value="3"></asp:ListItem>
                </asp:DropDownList>
            </asp:Panel>
          </ContentTemplate>
        </asp:UpdatePanel>
      </div>
    </form>
</body>
</html>
Share:
17,355
Lax_me
Author by

Lax_me

Updated on July 22, 2022

Comments

  • Lax_me
    Lax_me almost 2 years

    I have 3 textboxes , one is in updatepanel it will refresh for every 4 seconds. During refresh the controls which are not in update panel also loosing focus. I want to keep focus on those controls.

    Here is my code:

    <asp:UpdatePanel ID="upnlChat" runat="server">
        <ContentTemplate >
            <asp:TextBox ID="txtChatBox" ReadOnly="true" TextMode="MultiLine" 
                CssClass="mymultitextboxclass" runat="server"></asp:TextBox>
         </ContentTemplate>
          <Triggers>
          <asp:AsyncPostBackTrigger ControlID="timerChat" />
    
          </Triggers>
        </asp:UpdatePanel>
        <asp:Timer ID="timerChat" Interval="4000" runat="server" ontick="timerChat_Tick" ></asp:Timer>
            <table>
            <tr><td>User: </td><td colspan="2"><asp:TextBox ID="txtUser" runat="server" ></asp:TextBox><br /></td>
            <td>
                <asp:RequiredFieldValidator ID="RequiredUserName" runat="server" ErrorMessage="Username Required" ControlToValidate="txtUser" ></asp:RequiredFieldValidator> </td></tr>
            <tr><td>Message: </td><td><asp:TextBox ID="txtMsg" CssClass="mymsg" TextMode="MultiLine" onkeydown="if (event.keyCode == 13) { btnSend.focus(); this.form.submit();  }"  runat="server"></asp:TextBox></td>
            <td colspan="2"><asp:Button ID="btnSend" runat="server" onclick="btnSend_Click" 
                    OnClientClick="scroll()" Text="send" />
            </td></tr>        
            </table>
    

    Can anyone please help me?

  • Lax_me
    Lax_me about 11 years
    If I use this my textbox in update panel is not updating after asynchronous postback
  • santa
    santa over 10 years
    works like a charm, i use "document.activeElement.id" thou, because when the user tabs out of an autopostback-textbox into the next one "fe.id" will be the one that was left... i want to keep the focus in the one he just jumped into...
  • pinckerman
    pinckerman over 10 years
    While this link may answer the question, you should summarize or quote that article, because links tend to decay over time.
  • Dumitru Chirutac
    Dumitru Chirutac almost 10 years
    @sparebytes In IE8-IE10 inside of iframe not work, have you foresaw this case?
  • sparebytes
    sparebytes almost 10 years
    @DumitruChirutac, I guess you mean UpdatePanel > iframe >**Form Element*. No I didn't consider that case. That would take some additional checks.
  • Can Sahin
    Can Sahin about 8 years
    Nice script! I changed the events to add_pageLoading and add_pageLoaded instead of begin/endRequest (as suggested here). This ensures that the focus is set to the element active at the time when the async postback returns rather than the element active at the time when the async postback was started. If the postback takes some time and the user is fast tabbing through the controls, this will make a difference.
  • naasking
    naasking over 7 years
    This doesn't seem to work with tabs, at least in Chrome. The first async postback preserves the focus after tabbing to the next field, but for some reason, the second change followed by a tab causes a full postback instead of an async postback.