Greetings all,
I have a simple JQuery function which is bound to an ASP:Button and fires when the submit button is clicked, like this:
<asp:Button ID="btnSubmit" CssClass="btnSubmit" OnClick="btnSubmit_Click" runat="server"
Text="Send" />
$(document).ready(function () {
$(".btnSubmit").click(function () {
alert("button clicked");
});
});
This code runs correctly the first time the page is loaded, but never runs again after clicking Submit (and a post/postback occurs). The asp button code is within an UpdatePanel. It seems like the JQuery code is being “unregistered” or unbound after the postback. I have a ScriptManager control on the page but this is all I’m doing with it:
<asp:ScriptManager ID="ContactFormScriptManager" runat="server">
<Scripts>
<asp:ScriptReference Path="Scripts/jquery-1.4.1.js" ScriptMode="Auto" />
<asp:ScriptReference Path="Scripts/contact-form.js" ScriptMode="Auto" />
</Scripts>
</asp:ScriptManager>
I suspect there’s more I need to do with ScriptManager to make sure my JQuery code stays registered, but I’m not sure what. Your suggestions would be appreciated.
Thanks,
-NorthK
@Sarfraz is right about the solution but I thought you may want some explanation as to why this works:
It’s not that it’s being “unregistered”, it’s that the elements in the UpdatePanel are completely destroyed/replaced by new elements. Since the click handler is stored on those elements (well, not exactly, but close) it’s not automatically created for the new elements.
.live()however works differently, it adds an event handler todocumentwhich isn’t getting replaced. It listens for theclickevent to bubble up the DOM and reach document. When it gets there it checks if the element the event came from matches the selector…if the selector matches, it executes the handler.