How to intercept form submits reliably?
Asked Answered
K

1

6

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.

Kayo answered 18/10, 2010 at 9:0 Comment(1)
Oh, forgot to mention that "$('#bar').submit()" for the onChange part works as well. Does JS perform some kind of 'early-bind' on onX attributes?Kayo
L
10

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.

Lipstick answered 18/10, 2010 at 9:8 Comment(1)
Here is a drop-in replacement for onchange that doesn't require knowing the form id: onchange="$(this.form).submit()"Boreas

© 2022 - 2024 — McMap. All rights reserved.