Search code examples
jqueryasp.net-ajaxupdatepanelautopostback

Second time click of a button inside updatePanel, the event does not fire in jQuery


In my aspx file, I have:

<asp:UpdatePanel ID="UpdatePanel3" UpdateMode="Always" runat="server">
    <ContentTemplate>
       <asp:Button ID="Button1" runat="server" Text="Button" />
    </ContentTemplate>
</asp:UpdatePanel>

In my JavaScript file I have:

$('#ctl00_ContentPlaceHolder1_Button1').click(function (e) {
        alert('hello');
    });

But only the first time click on the button, I got alert('hello'), and no more alert messages afterwards.


Solution

  • For dynamic content, use jQuery's .live() method.

    $('#ctl00_ContentPlaceHolder1_Button1').live('click', function (e) {
        alert('hello');
    });
    

    Also, I'd recommend using a class instead of the ID. Using the ID is fragile to any code changes which affect the ASP.NET container/control structure:

    <asp:Button ID="Button1" runat="server" Text="Button" class="performsMyClickAction" />
    
    $('.performsMyClickAction').live('click', function (e) { ... }