Document.Ready() is not working after PostBack

Theomax picture Theomax · Mar 6, 2012 · Viewed 57.9k times · Source

I have a page that contains a user control within an update panel. $(document).ready(function() ) { is called and executes the code correctly when the page firsts loads but if the user clicks a button (within the user control), the document.ready() doesn't get called (document.load, onload also don't work)

I have researched this on the net and found similar problems but nothing that can explain why this isn't working. What other causes can there be for document.ready not working?

Answer

El Ronnoco picture El Ronnoco · Mar 6, 2012

This will be a problem with partial postback. The DOM isn't reloaded and so the document ready function won't be hit again. You need to assign a partial postback handler in JavaScript like so...

function doSomething() {
   //whatever you want to do on partial postback
}

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

The above call to add_endRequest should be placed in the JavaScript which is executed when the page first loads.