tags:

views:

73

answers:

3

I have an asp.net button on the page. I am trying to do this:

    $("#btn").click(function(e) {
        e.preventDefault();
        alert('hi');
    }

But the alert never shows up. I have to use an ASP.NET button only and not a HTML one.

+1  A: 

Make sure you reference the ClientID of the button, not the "normal" ID.

$("#<%= MyControl.ClientID %>").click(function() {
   alert(...);
   return false;
}

Also make sure this is inside a document.ready() handler:

$(document).ready(function() {
    $("#<%= MyControl.ClientID %>").click(function() {
       alert(...);
       return false;
    }
});
Philippe Leybaert
I still do not get the alert()..i have done exactly as you told
+1  A: 

Try to have the method return false as well and in your buttons onclick you add the javascript. Like this:

$("#btn").click(function(e) {
    e.preventDefault();
    alert('hi');
    return false;
}

or add it as an onclientclick function like this:

 function ClickFunction() {
     alert('hi');
     return false;
 }

 <asp:Button OnClientClick="return Clickfunction();" />
Robban
i do not want to use the onclientclick. It does not work even after using the precentdefault and return false
What you could do if you do not need the server functionality of the button is remove the runat="server" attribute. But then I would recommend using a standard <input type="button" /> instead.
Robban
A: 

Ok I got the answer over here

Using jQuery to Prevent ASP.NET Server Side Events from Occuring

I was missing the $(document).ready(function() . So silly of me!