mrwooster mrwooster - 3 months ago 5x
Javascript Question

Capture a form submit in JavaScript

There seems to be lots of info on how to submit a form using javascript, but I am looking for a solution to capture when a form has been submitted and intercept it in javascript.


<input type="text" name="in" value="some data" />
<button type="submit">Go</button>

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.


<form id="my-form">
    <input type="text" name="in" value="some data" />
    <button type="submit">Go</button>

In JS:

function processForm(e) {
    if (e.preventDefault) e.preventDefault();

    /* do what you want with the form */

    // You must return false to prevent the default form behavior
    return false;

var form = document.getElementById('my-form');
if (form.attachEvent) {
    form.attachEvent("submit", processForm);
} else {
    form.addEventListener("submit", processForm);

Edit: in my opinion, this approach is better than setting the onSubmit attribute on the form since it maintains separation of mark-up and functionality. But that's just my two cents.

Edit2: Updated my example to include preventDefault()