Execute javascript code straight before page submit

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
}

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
});

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
};

Tags:

Javascript