Javascript: Hijacking document.form.submit()

Earlier this week, I was helping a client of ours interface with a 3rd party widget on a site they work with. What the widget basically does is allow the user to input some information which is then POST’ed to another 3rd party site.

What our clients were looking to do was capture the information in the form before it was submitted, process it before the user left the page, and set any cookies on the user if necessary. Simple enough right? Use jQuery to trap the form’s submit event, do the processing dance, and then allow the form to submit normally.

So I implemented the code as described but for some reason the jQuery submit() handler was never being triggered. Perplexed, I looked through the actual widget code and it turns out that the widget was using a <a> tag with an onclick handler which eventually called document.someForm.submit(). Turns out, the jQuery submit() handler won’t trigger when a form is submitted in this fashion.

Thankfully, it’s relatively straightforward to get around this. You just need to override the form element’s submit() function with one of your own and then eventually call the original function once you’re done.

Well thats about it – As always, questions and comments welcome.