Rebinding events in jQuery after Ajax update (updatepanel)

asp.netJqueryasp.net AjaxUpdatepanel

asp.net Problem Overview


I have several input and option elements on my page, each (well almost) have an event attached to update some text on the page once they change. I use jQuery which is really really cool :)

I also use Microsofts Ajax framework, utilizing the UpdatePanel. The reason why I do that is that certain elements are created on the page based on some server-side logic. I don't really want to explain why I use the UpdatePanel - even if it could (it can with quite some effort) be rewritten to use only jQuery I still want that UpdatePanel.

You probably guessed it - once I have a postback on the UpdatePanel the jQuery events stops working. I actually was expecting this, since the "postback" is not really a new postback so my code in document.ready that binds the events won't be fired again. I also confirmed my suspicion by reading up on it in the jQuery help libraries.

Anyway I'm left with the problem of rebinding my controls after the UpdatePanel is done updating the DOM. I preferably need a solution that does not require adding more .js files (jQuery plug-ins) to the page but something as simple as being able to catch the UpdatePanel's 'afterupdating' where I can just call my method to rebind all the form elements.

asp.net Solutions


Solution 1 - asp.net

Since you're using ASP.NET AJAX, you'll have access to a pageLoad event handler, that gets called each time the page posts back, be it full or partial from an UpdatePanel. You just need to put the function in to your page, no hooking up is required.

function pageLoad(sender, args)
{
   if (args.get_isPartialLoad())
   {
       //Specific code for partial postbacks can go in here.
   }
}

Solution 2 - asp.net

Or you could check the latest jQuery's live functionality via the on() method.

Solution 3 - asp.net

Sys.Application.add_load(initSomething);
function initSomething()
{
  // will execute on load plus on every UpdatePanel postback
}

Solution 4 - asp.net

As of jQuery 1.7, the recommended way to do this is to use jQuery's .on() syntax.

Make sure, however, that you set up the event on the document object, not the DOM object itself. For example, this will break after the UpdatePanel postback:

$(':input').on('change', function() {...});

... because the ':inputs' have been rewritten. Do this instead:

$(document).on('change', ':input', function() {...});

As long as the document is around, any inputs (including those from UpdatePanel refreshes) will trigger the change handler.

Solution 5 - asp.net

Use following code

Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoaded);

function pageLoaded(sender, args) {
    var updatedPanels = args.get_panelsUpdated();
    // check if Main Panel was updated 
    for (idx = 0; idx < updatedPanels.length; idx++) {
        if (updatedPanels[idx].id == "<%=upMain.ID %>") {
            rebindEventsForMainPanel();
            break;
        }
    }
}

Solution 6 - asp.net

You could use jQuery and event delegation. Basically hook events to containers rather than every element and query the event.target and run script based on that.

It has multiple benefits in that you reduce the code noise (no need to rebind). It is also easier on browser memory (less events bound in the DOM.)

Quick example here.

jQuery plugin for easy event delegation.

P.S I am 99% sure delegation will be in the jQuery core at the next release.

Solution 7 - asp.net

Use the following code, You need to validate the control will use the datapicker:

    <script type="text/javascript" language="javascript">

         Sys.WebForms.PageRequestManager.getInstance().add_endRequest(addDataPicker); 
         function addDataPicker(sender, args)
         {
            var fchFacturacion = document.getElementById('<%= txtFechaFacturacion.ClientID %>');
            if (fchFacturacion != null) {
               $(fchFacturacion).datepicker({ onSelect: function () { }, changeMonth: true, changeYear: true, showOn: 'button', buttonImage: '../Imagenes/calendar.gif', buttonImageOnly: true});}
         } 

    </script>

     <asp:UpdatePanel ID="upEjem" runat="server" UpdateMode="Conditional">
       <ContentTemplate>
              <div id="div1" runat="server" visible="false">
                  <input type="text" id="txtFechaFacturacion" 
                      name="txtFechaFacturacion" visible="true"
                      readonly="readonly" runat="server" />
              </div>
       </ContentTemplate>
     </asp:UpdatePanel>

Solution 8 - asp.net

         <script type="text/javascript">
             function pageLoad() {
                 
                 if (Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) {


       }
             
            </script>

        </ContentTemplate>
    </asp:UpdatePanel>

into of the "if" you can put the code that you need execute every time that the updatepanel does AsyncPostBack.

Solution 9 - asp.net

Bind your events using jQuery's new 'live' method. It will bind events to all your present elements and all future ones too. Cha ching! :)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPer Hornsh&#248;j-SchierbeckView Question on Stackoverflow
Solution 1 - asp.netPhil JenkinsView Answer on Stackoverflow
Solution 2 - asp.netGeorgeView Answer on Stackoverflow
Solution 3 - asp.netPauliusView Answer on Stackoverflow
Solution 4 - asp.netlambinatorView Answer on Stackoverflow
Solution 5 - asp.netshatlView Answer on Stackoverflow
Solution 6 - asp.netredsquareView Answer on Stackoverflow
Solution 7 - asp.netrocke_amigaView Answer on Stackoverflow
Solution 8 - asp.netcivanmView Answer on Stackoverflow
Solution 9 - asp.netJohn StricklerView Answer on Stackoverflow