Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have ASP.NET Button execute jQuery code

Tags:

jquery

c#

asp.net

I have jquery code on cc.js that I need to execute when an asp.net button is clicked.

The code on cc.js has a variable called settings and then submits these settings to an API (POST action) with the following code:

'Transaction Submit'
 $.ajax(settings).done(function (response) {
    console.log(response);
});

Basically I need this button <asp:Button ID="BtnSubmit" runat="server" Text="Submit" /> to execute that jquery code. How can I do so?

like image 317
Ayo Avatar asked Dec 18 '22 14:12

Ayo


1 Answers

You are looking for the OnClientClick property

<asp:Button ID="BtnSubmit" runat="server" OnClientClick="JSFunctionName(); return false;" Text="Submit" />

You will need to add the additional return false statement to prevent a post back from occurring if you button element is located inside a form.

This is assuming you want to decouple your front end html from your js code by using an inline call. If that is not the case then you mod your cc.js to autobind on the element as others have mentioned. One thing they left out is that in that process is that IF you button is inside a form then you need to prevent the auto-post back like so:

$(document).ready(function() {

  $("#BtnSubmit").click(function(){
    JSFunctionName();
    e.preventDefault();
  });

});
like image 104
Travis Acton Avatar answered Dec 24 '22 02:12

Travis Acton