Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Click event on asp:button

Tags:

jquery

asp.net

I have a server side button as

<asp:Button ID="btnSummary" runat="server" OnClick="btnSummary_Click" Text="Next" />

I want to attach the jQuery Click event using its ID and NOT using the alternative class attribute way.

I tried to attach the click event as:

$("#btnSummary").click(function() 
        {
            alert("1");
        });

But, its click event is not fired. Also, I have also tried $("id[$btnSummary]").

Is there any way to attach the click event on asp:button using jQuery without the class attribute on the button?

like image 994
Sachin Gaur Avatar asked Nov 28 '22 06:11

Sachin Gaur


2 Answers

Some of the options you have can be found here

How to stop ASP.NET from changing ids in order to use jQuery

EDIT:

After reading your comments on other answers, it sounds like you need to bind the onclick event handler inside of ASP.NET AJAX's pageLoad, so that it is bound on every postback, including asynchronous postbacks. On the other hand, $(document).ready() binds only once on initial page load

function pageLoad(sender, args)
{
     $("#<%=btnSummary.ClientID %>").click(function() 
    {
        alert("1");
    });
}

Dave Ward wrote a nice article on the difference between pageLoad and $(document).ready().

like image 136
Russ Cam Avatar answered Dec 11 '22 04:12

Russ Cam


Add ClientIDMode="Static" to your asp:button, something like this:

<asp:Button ID="Button1" runat="server" ClientIDMode="Static" Text="Button" />

This will make the ID remain the same. It disables the autogenerated names for this control.

Here is the reference for this: http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientid.aspx

like image 36
Luis Coell Avatar answered Dec 11 '22 04:12

Luis Coell