When a user presses the submit button, I do not want the form to be submitted, but instead I would like a JavaScript function to be called.

function captureForm() {
// do some stuff with the values in the form
// stop form from being submitted
}

A quick hack would be to add an onclick function to the button but I do not like this solution... there are many ways to submit a form... e.g. pressing return while on an input, which this does not account for.

@Micheal... This code does not appear to work... the function gets executed, but the form still gets submitted, even with the return false. See gist.github.com/881177 alert('ho') should only be triggered once.
–
mrwoosterMar 22 '11 at 13:03

Follow up: Is there a way to capture a form submit with JavaScript without affecting the browser's handling of the required attribute?
–
ElisabethNov 20 '11 at 23:18

@Elisabeth What handling of what attribute? If you mean to not prevent the form from actually being submitted, you just need captureForm() to return true instead of false.
–
kbaNov 20 '11 at 23:30

The browser's handling of the "required" attribute. I do want to prevent the form from being submitted. But by returning false instead of true (or using preventDefault()), it changes how the browser handles the "required" attribute on an input element. Try it for yourself: add <code>required</code> to an input element, capture the submit and see if you lose the default behavior for it.
–
ElisabethNov 21 '11 at 0:43

I don't seem to lose default behaviour. It works fine in Chrome. You'll need to come up with an erroneous example in order for me to help.
–
kbaNov 21 '11 at 1:08

// Should only be triggered on first page load
alert('ho');
window.onload=function() {
document.getElementById('my-form').onsubmit=function() {
/* do what you want with the form */
// Should be triggered on form submit
alert('hi');
// You must return false to prevent the default form behavior
return false;
}
}

So, the solution to add an event handler for onsubmit and to call preventDefault() or return false makes this work for me. However, using either preventDefault() or return false causes the required attribute check to fail (test in Opera 11+ to see).

Is there a way to capture a form submit with JavaScript without affecting the browser's handling of the required attribute?