Jquery function BEFORE form submission Jquery function BEFORE form submission jquery jquery

Jquery function BEFORE form submission


You can use the onsubmit function.

If you return false the form won't get submitted. Read up about it here.

$('#myform').submit(function() {  // your code here});


$('#myform').submit(function() {  // your code here})

The above is NOT working in Firefox. The form will just simply submit without running your code first. Also, similar issues are mentioned elsewhere... such as this question.The workaround will be

$('#myform').submit(function(event) { event.preventDefault(); //this will prevent the default submit  // your code here (But not asynchronous code such as Ajax because it does not wait for a response and move to the next line.)   $(this).unbind('submit').submit(); // continue the submit unbind preventDefault})


Based on Wakas Bukhary answer, you could make it async by puting the last line in the response scope.

$('#myform').submit(function(event) {  event.preventDefault(); //this will prevent the default submit  var _this = $(this); //store form so it can be accessed later  $.ajax('GET', 'url').then(function(resp) {    // your code here    _this.unbind('submit').submit(); // continue the submit unbind preventDefault  })  }