Parry
Parry

Reputation:

ASP.NET Button causes a postback

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.

Upvotes: 4

Views: 1611

Answers (3)

Parry
Parry

Reputation:

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!

Upvotes: 1

Philippe Leybaert
Philippe Leybaert

Reputation: 171914

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;
    }
});

Upvotes: 1

Robban
Robban

Reputation: 6802

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();" />

Upvotes: 1

Related Questions