Reputation: 11820
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).
Upvotes: 41
Views: 62896
Reputation: 1723
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
Upvotes: 3
Reputation: 678
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.
Upvotes: 0
Reputation: 3721
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
}
Upvotes: 59
Reputation: 165971
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
};
Upvotes: 8
Reputation: 3869
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
});
Upvotes: 30