The form that left
The other day, I encountered a form submission behavior I didn’t expect, nor don’t have any solution for.
Take this obtrusive code example (same thing happens with unobtrusive approaches):
<span onclick="document.getElementById('da-form').submit();">Spank the monkey</span>
<form id="monkey" action="somewhere.php" method="get" onsubmit="return alert('Spanked')">
When the submit() method of a form element is called, it doesn’t trigger the onsubmit event handler(s) applied to the form. This goes for all web browsers, quirks and standards mode.
Yes, it really is so
After discussing with lots of people, who were as surprised as me, I found this excerpt from David Flanagan’s excellent JavaScript book, JavaScript - The Definitive Guide:
Calling the submit( ) method of a form does not trigger the onsubmit handler.
So, this behavior is confirmed, although I can’t seem to find any explanation as to why it is so. And this really baffles me, since there are definitely scenarios where one would like to validate the actual form input before submitting it.
Where it becomes a real problem
But how about just validating it before you call the submit() method, you say?
In an application where you have control, sure. But consider all .NET and MOSS applications out there which rely on a hideous feature called __doPostBack. It’s a JavaScript function, probably written in the last century, which calls the submit() methods of form elements to submit them, and, trust me, this usage is very well spread over the Internet.
And in those scenarios, there’s no way to perform a proper client-side validation, unless you rely on some of those frameworks’ own validation methods, which completely takes away the chance to write general and optimized validation scripts, centrally located in a JavaScript file which will be cached for all pages on the web site in question
An alternative solution
I was talking to my Canadian friend Jonathan Snook, and he proposed a solution:
Override the __doPostBack function in every page, but save a reference to it, so you can call it later. For example:
var oldDoPostBack = __doPostBack;
function __doPostBack (eventTarget, eventArgument) {
// Do your own validation first
if (itsActuallyvalid()) {
oldDoPostBack(eventTarget, eventArgument);
}
}
Happy workarounding! ![]()


