2

Does adding a jquery submit handler guarantee that the event handler is completed before the form submits?

When a form is submitted, I want to first do an action, then let the form submit event continue.

I'm having a hard time telling if my event is always done before the form submits, or if this is actually just by chance due to timing with the js running before the post request sends and the next page loads.

$('.myform').submit(function(){
  // Do something.
  $('.myForm some_input').val("Hi!");

  // Then submit the form as normal.
});
Don P
  • 60,113
  • 114
  • 300
  • 432
  • check http://stackoverflow.com/questions/6912197/change-value-of-input-then-submit-form-in-javascript – Yuliam Chandra Jul 09 '14 at 06:50
  • but after form submit page will refresh and you will not see any change in some_input. – Bhushan Kawadkar Jul 09 '14 at 06:51
  • 5
    According to [the documentation](http://api.jquery.com/submit) : `This happens prior to the actual submission, so we can cancel the submit action by calling .preventDefault() on the event object or by returning false from our handler` – Sylvain Jul 09 '14 at 06:51
  • Thanks a lot @Sylvain, thats also a really good point about it handling preventDefault, so it should've been obvious that these events are handled first. Makes me curious if I attach two event handlers, and each of them has e.preventDefault which fires first. – Don P Jul 09 '14 at 06:55
  • @YuliamChandra - accepted answer users inline JS in HTML, and it's not about jquery behavior – Don P Jul 09 '14 at 06:55
  • @BhushanKawadkar - if I was submitting the form to the same page, and if I was trying to show the input value to a user, then yes your comment is true I guess... – Don P Jul 09 '14 at 06:57
  • @DonnyP, check this http://jsbin.com/pojucapu/2/edit – Yuliam Chandra Jul 09 '14 at 07:03
  • 1
    You could use a function that has a return of true. So your code then return true then you can do something like. `function ifFinished(){if(codeExecuted==true){ $(form).submit() } ` I'm on my phone so its not perfect but hope you get it. – EasyBB Jul 09 '14 at 07:10

0 Answers0