Tuesday, 24 September 2013

Submitting forms programmatically

Very short one today, folks, because something surprised me: If you use jQuery to submit a form programmatically, it will trigger submit handlers on the form. This surprised me because if you use the DOM to do it, it doesn't. Consider this HTML:

<form id="theForm" action="http://blog.niftysnippets.org" target="_blank" method="GET">
    <p>This one will trigger the submit handler:</p>
    <input type="submit" value="Click to send form normally">
</form>
<p>So will this one (which surprised me):</p>
<input type="button" id="jQuerySubmit" value="Click to use jQuery to send the form">
<p>This one won't (standard DOM behavior):</p>
<input type="button" id="domSubmit" value="Click to use HTMLFormElement#submit to send the form">

And this code (below the above in the HTML file):

$('#theForm').submit(function() {
  alert("jQuery submit handler called");
})[0].onsubmit = function() {
  alert("DOM submit handler called");
};

$("#jQuerySubmit").click(function() {
  $("#theForm").submit();
});

$("#domSubmit").click(function() {
  $("#theForm")[0].submit();
});

Clicking the jQuerySubmit button triggers the handlers, clicking the domSubmit button does not. Live copy

So if, like me, you're used to that handler not getting called when you submit programmatically, well, jQuery changes that! If you want the old behavior, use the DOM directly (it's only three more characters :-) ).

Happy coding!