Adding a jQuery click event to an asp: button, which fires before the button postbacks

I have an asp.net application with an asp: button, which causes a postback, which means that the html for input has an onclick attribute that is automatically generated, I need to add an event via jQuery to the onclick attribute, which before automatic generated reverse gear.

Below is an example of the html created, I need to make sure that my event added by jQuery fires before the WebForm_DoPostBackWithOptions () function.

<input id="ctl00_MainContent_Save" type="submit" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$MainContent$Save", "", true, "", "", false, false))" value="" name="ctl00$MainContent$Save"> 

for clarity, I know that I can add an event through jQuery as follows:

 $('#ctl00_MainContent_Save').click(function() { somfunction(); }); 

but I want my event to fire before WebForm_DoPostBackWithOptions

+4
source share
3 answers

You can probably try the mousedown event, which will fire before the click event fires.

 $('#ctl00_MainContent_Save').mousedown(function() { somfunction(); }); 

or try the code below

 $(document).ready(function(){ $('#ctl00_MainContent_Save') .attr("onclick", null) .removeAttr("onclick") .click(function() { somfunction(); WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions($(this).attr("name"), "", true, "", "", false, false)); }); }); 
+4
source

Hope this gives you an idea of ​​how to do this.

 <asp:Button ID="bsrc" runat="server" Text="Search" OnClick="bsrc_Click" /> <script type="text/javascript" language="javascript"> $(document).ready(function() { $('#<%= bsrc.ClientID %>').click(function(e) { return true; }); }); </script> 

When you click the button first, it will call the javascript function and then go to the server. If you want to stop calling a server event from javascript code only return false; instead return true;

+2
source

What about:

 <input id="ctl00_MainContent_Save" type="submit" value="" name="ctl00$MainContent$Save"> ... $('#ctl00_MainContent_Save').click(function(e) { e.preventDefault(); somfunction(); WebForm_DoPostBackWithOptions( new WebForm_PostBackOptions("ctl00$MainContent$Save", "", true, "", "", false, false))" }); 

If you cannot change the HTML, you can try (warning: unverified!)

 var $link = $('#ctl00_MainContent_Save'); var oldFunction = $link[0].onClick; $link[0].onClick = null $link.click(function(e) { e.preventDefault(); somfunction(); oldFunction(); }); 
0
source

All Articles