180

i have a form which has a button that submits the form. I need to do something before submits happen. I tried doing onClick on that button but it happens after the submit.

I can't share the code but, generally, what should I do in jQuery or JS to handle this?

FranciscoBouza
  • 590
  • 6
  • 19
Jimmy
  • 10,427
  • 18
  • 67
  • 122
  • 2
    @Brad Christie if only i could accept comment as an answer. Thanks very helpful. – Jimmy Nov 14 '11 at 02:22
  • 7
    I hate it when stackover closes a question. You can handle your actions using the following events that fire on the following timing just before submitting a form: 1- onmouseover 2- onmousemove 3- onmousedown 4- onfocus 5- onmouseup 6- onclick 7- onsubmit – Shadi Alnamrouti Feb 02 '17 at 23:24
  • On vanilla JS/HTML: `
    ...` use the 'onsubmit'
    – Manatax Feb 02 '18 at 01:13
  • you don't have to share code. you can send in a sample of what you are asking. Or else why are you not able to solve your own problems alone? – webs Dec 31 '19 at 13:24
  • "It's difficult to tell what is being asked here." Hilarious. A closed question with 153 votes, 14 bookmarks, an answer with 221 votes... and counting. – Luke Aug 20 '21 at 02:33

5 Answers5

254

If you have a form as such:

<form id="myform">
...
</form>

You can use the following jQuery code to do something before the form is submitted:

$('#myform').submit(function() {
    // DO STUFF...
    return true; // return false to cancel form action
});

Update; for newer JQuery versions (to avoid deprecation warnings), try:

$('#myform').on('submit', function() {

    // ...

    return true;
});
Top-Master
  • 7,611
  • 5
  • 39
  • 71
Dan Breen
  • 12,626
  • 4
  • 38
  • 49
  • 4
    I'm having troubles using this for loops that have to be completed before the submit. Any suggestions? – Smilyan Jun 03 '13 at 08:58
  • Got any code to look at? Not sure I understand the problem. – Dan Breen Jun 03 '13 at 13:51
  • 3
    Why is this wrapped in an empty function call? Shouldn't the `submit` function be able to bind directly to the `$('#form')` without the surrounding empty function? EDIT: [the docs suggest that the surrounding function call is not needed](https://api.jquery.com/submit/#submit-eventData-handler). – eykanal Aug 01 '16 at 13:44
  • @eykanal Good point. I went ahead and edited the answer to remove the function wrapper after confirming that it does work fine with it removed. – Jon Schneider Sep 16 '16 at 19:37
  • 4
    @eykanal I used the "empty" function call, because that's a shorthand for jQuery's `$(document).ready()` function, which ensures the DOM is complete before attaching the `submit` event. If your JS is at the bottom of the page, it's not necessary, but if it's in the `` section then you need it. See: http://stackoverflow.com/q/13062246/135108 – Dan Breen Oct 05 '16 at 16:29
  • Is there a way to this using JavaScript? – Inaara Kalani Mar 03 '23 at 07:28
27

Assuming you have a form like this:

<form id="myForm" action="foo.php" method="post">
   <input type="text" value="" />
   <input type="submit" value="submit form" />

</form>

You can attach a onsubmit-event with jQuery like this:

$('#myForm').submit(function() {
  alert('Handler for .submit() called.');
  return false;
});

If you return false the form won't be submitted after the function, if you return true or nothing it will submit as usual.

See the jQuery documentation for more info.

acme
  • 14,654
  • 7
  • 75
  • 109
12

You can use onclick to run some JavaScript or jQuery code before submitting the form like this:

<script type="text/javascript">
    beforeSubmit = function(){
        if (1 == 1){
            //your before submit logic
        }        
        $("#formid").submit();            
    }
</script>
<input type="button" value="Click" onclick="beforeSubmit();" />
James Johnson
  • 45,496
  • 8
  • 73
  • 110
  • 23
    But this doesn't work, when the form contains e.g. an input field an the user is hitting the return key which is firing the submit event. It's usually better to attach directly to the submit event so you can ensure it gets called regardless how the user fired the submission. – acme Nov 10 '11 at 09:49
  • 2
  • 5
    @Ansyori That's even worse! – Dai Jul 24 '21 at 09:05
  • You can sumbit with Enter, you don't have to click anything – mileusna May 10 '23 at 01:01
6

make sure the submit button is not of type "submit", make it a button. Then use the onclick event to trigger some javascript. There you can do whatever you want before you actually post your data.

rogerlsmith
  • 6,670
  • 2
  • 20
  • 25
  • 8
    The form can be submitted in a number of ways, such as pressing enter in certain fields. Binding to a click on one button that may not be clicked, is not a good idea. The other answers show how you bind `onsubmit` of the *form*, which will fire no matter how the form is submitted. – Jason Aug 11 '17 at 21:26
  • 3
    Surprisingly, here in 2021, `onClick` of the `type="submit"` is triggered by doing anything that would anyway ultimately lead to the form.submit() action. Works with pressing enter on an input field, on Firefox, Chrome, and Brave. Who knows if that was the case ten years ago. – HoldOffHunger Oct 30 '21 at 19:57
5

Form:

<form id="formId" action="/" method="POST" onsubmit="prepareForm()">
   <input type="text" value="" />
   <input type="submit" value="Submit" />
</form>

Javascript file:

function prepareForm(event) {
  event.preventDefault();
  // Do something you need
  document.getElementById("formId").requestSubmit();
}

Note: If you're supporting Safari (which you probably are) you'll need to pull in a polyfill for requestSubmit()

Yurii Stefaniuk
  • 1,594
  • 2
  • 11
  • 16