Accendo / Publikované

ASPX Textbox – Losing focus after autopostback

Autor:  Libor Bešenyi

Dátum:  25.2.2012

 

We have used textboxes with autopostback inner in Ajax update panel. There was an error with losing focus (tab key pressed), because on change event was raised first. We have resolved it with jQuery. Incremented element problem:

 

<asp:TextBox ID="TextBoxStoreys" runat="server" Width="60px" AutoPostBack="true"

 />

 

Pressing tab on this control fired server-side on change event (this is correct), but next focused element was lost. We implemented to general master page hidden field which holds last fired element ID and 2 java-script routine. First stored fired control ID and second has catch ending of asynchronous request. Than find next possible element (which will be focused manually).

 

...

<asp:HiddenField ID="hiddenFieldLastAutopostbackFiredElement" runat="server" />

...

       <script type="text/javascript">

             //<![CDATA[

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

                    function (sender, e)

                    {

                           // #6220 Save latest focus (textbox autopostback issue)

                           var inputHoldsLastFocus = getElement("hiddenFieldLastAutopostbackFiredElement");

                           if (inputHoldsLastFocus.value)

                           {

                                  var lastControl = getElement(inputHoldsLastFocus.value);

 

                                  // Focus next control

                                  var allPossibleElements = $('input:text');

                                  var index = allPossibleElements.index(lastControl);

 

                                  if (index >= 0 && index + 1 < allPossibleElements.length)

                                  {

                                        var nextElement = allPossibleElements[index + 1];

                                        nextElement.focus();

                                        nextElement.select();

                                  } // if

 

                                  inputHoldsLastFocus.value = null;

                           } // if

                    });

 

             function AutoPostBackTextBox(control)

             {

                    // #6220 Save latest focus (textbox autopostback issue)

                    var inputHoldsLastFocus = getElement("hiddenFieldLastAutopostbackFiredElement");

                    inputHoldsLastFocus.value = control.id;

 

                    __doPostBack(control.id, "");

             }

             //]]>

       </script>

</asp:Content>

 

AutoPostback on the textbox was removed, as you can see is postback raised within the storing the last element ID:

 

<asp:TextBox ID="TextBoxStoreys" runat="server" Width="60px" onchange="javascript: AutoPostBackTextBox(this);" />