40

There are a few similar questions to this but none quite the same.

I want to know if there is an event that can be used to execute some JS before a page is submitting (i.e. POSTed).

Toon Krijthe
  • 52,876
  • 38
  • 145
  • 202
ale
  • 11,636
  • 27
  • 92
  • 149

5 Answers5

59

Something like this?

<form onsubmit="do_something()">

function do_something(){
   // Do your stuff here
}

If you put return like the code below, you can prevent the form submission by returning false from the do_something() function.

<form onsubmit="return do_something()">

function do_something(){
   // Do your stuff here
   return true; // submit the form

   return false; // don't submit the form
}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Moe Sweet
  • 3,683
  • 2
  • 34
  • 46
30

If you are working with the form, you can use onsubmit event.

Using jQuery you can do that with

$('#myform').submit(function() {
  // your code here
});
Laurynas
  • 3,829
  • 2
  • 32
  • 22
8

You can bind an event handler to the submit event (following code assumes you have an id on your form):

document.getElementById("someForm").onsubmit = function() {
    //Do stuff
};
James Allardice
  • 164,175
  • 21
  • 332
  • 312
3

Yes, you can use on the onsubmit event on your form.

In pure HTML (without jQuery), you can use:

<form onSubmit="mySubmitFunction()">
   ...
</form>

More details here: https://www.w3schools.com/jsref/event_onsubmit.asp

Julien Bourdon
  • 1,713
  • 17
  • 28
0

The following code will abort the submission from the window level, which will not submit the form.

window.onsubmit = function() { alert('aborting submit'); return false; };

Tested with IE11, so it should work for some legacy applications without jQuery.

Vince Pike
  • 620
  • 6
  • 13