views:

149

answers:

3

Hi,

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 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'). no more alert messages afterwards. Any advices on this, please?

Thanks in advance.

A: 

I'm wondering why you have your selector as #ct_100_ContenPlaceHolder1_Button1. I switched it to #Button1 and it appeared to work fine for me.

JasCav
Because you did not place it inside of a PLaceHolder. It works fine for the first time, but second time, it did not fire :(
JoesyXHN
A: 

When the UpdatePanel does its asynchronous callback, you lose your jquery event registration, because the contents of the panel get completely replaced.

You can execute more JavaScript to re-wire things up by adding a script registration to the script manager during your callback. Something like this should get you close (in your button's server-side click handler):

ScriptManager.RegisterStartupScript(
    this,
    GetType(),
    "AnyStringYouWant",
    "$('#ctl00_ContentPlaceHolder1_Button1').click(function (e) {alert('hello');});",
    true);
kbrimington
it sounds interesting!Could you please let me know where should I place it?
JoesyXHN
It looks like you have your answer already, but in response to your comment, you could use this code in your code-behind, probably anywhere before the Render stage of the page lifecycle. OnLoad should be fine.
kbrimington
Yes, that works fine as well but I prefer to use 'live' as the answer above in jQuery. It works super!Thanks!
JoesyXHN
+1  A: 

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) { ... }
fearofawhackplanet
haha yes, using live working fine.Great! Thanks a lot!
JoesyXHN
Thank you because I am using several divs with the same class css and I need to do some events for a certain div therefore I am calling the div using its ID. Thanks for your advise as well!
JoesyXHN

related questions