jQuery Submit Event Happens Twice

Chris W. picture Chris W. · Mar 29, 2011 · Viewed 10.1k times · Source

My jQuery submit() event is firing twice, and I don't know why.

I'm using a templating engine to build my HTML dynamically so I end up calling $(document).ready() multiple times, as follows...

<script>
$(document).ready(function() {
    $("form.search input[type='image']").click(function() { $(this).closest('form.search').submit() })
})
</script>

...later...

</script>
$(document).ready(function() {
    # I have put an `unbind('submit')` in here to be sure I have nothing else but this particular function bound to `submit`
    $('form.search').unbind('submit').bind('submit',function(event) {
        event.stopPropagation();
        search_term = $(this).find('input[type=text]').val()
        $new_keyword = $('<li class="filter keyword selected" name="'+search_term+'">'+search_term+'</li>')
        alert('event fired!')
        $("#keywords ul").append($new_keyword)
        do_search_selected()
        return false; // Stop the form from actually submitting
    })
})
</script>

The Form HTML:

<form class="search" method="get" action="/search/">

    <div>
        <input id="searchfield"type="text" name="keywords" value="Search" />
        <input id="searchbutton" type="image" src="{{ media_url }}images/search.png" />
     </div>
</form>

(FYI: When I run this in the Safari console $('form.search').get() I get this [ <form class=​"search" method=​"get" action=​"/​search/​">​…​</form>​ ])

The problem:

When I hit Enter or click the submit button or otherwise trigger the submit event, the event is fired twice. I know this because an <li> is added twice to the dom and the alert appears twice as well.

The culprit:

When I comment out the click event binding in the first $(document).ready call, the event only occurs once, as expected. How can the code in the first be causing the double event trigger?

Answer

Chris W. picture Chris W. · Mar 29, 2011

The problem was in the first $(document).ready() function. I bound the click event of an input[type=image] to trigger a submit event on my form, but it turns out that image inputs already do a submit when clicked by default.