Monday, January 11, 2016

How can I put a JavaScript onclick event on a web forms button when it already has a C# OnClick event?

At this...

<asp:Button ID="Foo" runat="server" Text="Go" OnClick="Foo_Click" />

 
 

The OnClick is going to correspond to something in the code behind like so:

protected void Foo_Click(object sender, EventArgs e)
{
   var whatever = "meh";
}

 
 

If you try to jam in a second onclick for JavaScript at the tag itself you will get this error:

The tag contains duplicate 'onclick' attributes.

 
 

Oh no! How do we get out of this pit of spiders? Well, here is one way to assign a second onclick event with jQuery:

$("#<%= Foo.ClientID %>").attr("onclick","return false;");

 
 

What is below is just a smidge better as it works with IE7 whereas the thing above does not.

$("#<%= Foo.ClientID %>").bind('click', function () {
   return false;
});

 
 

If you want to keep the button from submitting the web form you may have to have the return false; immediately there at the binding. I tried to put it in a function and call out to the function and, at least in Chrome, it didn't work.

No comments:

Post a Comment