How to intercept form submits reliably?

Felix Schwarz picture Felix Schwarz · Oct 18, 2010 · Viewed 13.7k times · Source

I'm trying to intercept all kind of form submissions for a specifc form on a web page. It looks to be very simple with jQuery: form.submit(function(e) {…}) and it works beautifully if I click the submit button.

However there is also an onChange property on a select field which does this.form.submit() and it looks like this call circumvents my listener (in Chromium/Firefox):

<script type="text/javascript">
    function submitForm(e) {
        window.alert('submitted');
        e.preventDefault();
        return false;
    }

    $(document).ready(function() {
        $('#bar').submit(submitForm);
    });
</script>

<form id="bar">
    <select name="name" onChange="this.form.submit()">
        <option>Foo</option>
        <option>Bar</option>
    </select>
    <br/>
    <input type="submit"/>
</form>

Obviously in the code above I could just change this.form.submit() to a specific reference of my submit listener. However in my real app it's not that simple so I'm looking for way where I don't have to modify the onChange property.

If I did not do a stupid mistake but this is actually expected browser behavior, I'd be really glad if you could explain the event flow and why this leads to the symptoms described above.

Answer

Fr&#233;d&#233;ric Hamidi picture Frédéric Hamidi · Oct 18, 2010

Calling the form.submit() method does not trigger the submit event, just like e.g. setting the value of a text box does not trigger its change event. Try to trigger the submit event through jQuery instead:

<form id="bar">
    <select name="name" onChange="$('#bar').submit();">
        <option>Foo</option>
        <option>Bar</option>
    </select>
    <br/>
    <input type="submit"/>
</form>

According to the documentation, the default submit action on the form will be fired and the form will be submitted.