JavaScript onSubmit Handler

I think I’ve actually read this before, but I had forgotten it (for which I paid 30-45 minutes of debugging hell – why won’t you work? Stoopid JavaScript!).

If you are submitting a form using JavaScript (document.formName.submit(); ), with an onclick event, the onsubmit handler on the form (say a validation script) does not fire. You need to call the script you want to run onsubmit in the onclick event.

<script language="JavaScript">
function validate() {
return true;
}
</script>
<form name="foo"
action="index.php"
method="post"
onsubmit=" if (!validate()) { alert('whoops!'); return false; }">
<input type="text" name="bar" />
<span onclick="if (!validate()) { alert('whoops!'); return false; }
else { document.foo.submit(); }">
Submit
</span>
</form>