2

I have a large .aspx page, with multiple server controls. And, there is also a JavaScript file referenced by this .aspx page. I want to have a JavaScript function within this existing .js file, that will get called before any postback that happens to the server.

[note: I have seen another post that mention how to do this in JQuery ( How to capture submit event using jQuery in an ASP.NET application? ), but I would like that to be done through the existing JavaScript file, rather than using a new technology like JQuery]

[Edited] Solution of using OnSubmit handler will not work for me...because it will not get called for postbacks that get triggered by server controls.

Community
  • 1
  • 1
user632942
  • 443
  • 4
  • 8
  • 16

1 Answers1

3

You need something like this:

/* 
   usually there is only one form in asp.net, but if you know you can have 
   more than one, you can get main form with document.getElementById
*/
var form = document.getElementsByTagName("form")[0];     
if (form.addEventListener) {
    form.addEventListener('submit', functionThatShouldBeCalledBeforeSubmit, false); 
} else if (form.attachEvent)  {
    form.attachEvent('onsubmit', functionThatShouldBeCalledBeforeSubmit);
}

onsubmit event will rise any time form is submitted. No matter how.

More details about attaching events with JS: https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener

Viktor S.
  • 12,736
  • 1
  • 27
  • 52
  • 2
    "//asp.net allows only one form on a page" - not quite right. you can have as many forms as you like. You can only have one server-side form visible at any time. So you would be better getting the form by its ID. Just my 2 cents :) – Darren Wainwright Nov 09 '12 at 18:02
  • @Darren Hm... yes. If it is outside runat="server" form, it will be sent to client (just checked that) ). Agree. I tried to place it inside .ascx control and it was silently removed by asp.net and that misleaded me. – Viktor S. Nov 09 '12 at 18:12
  • This will not work for the postbacks that get triggered by server controls, right? – user632942 Nov 09 '12 at 18:18