jQuery Submit Event Happens Twice
Solution 1
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.
Solution 2
Selecting the form and preventing the default submit handler should all work as you describe it. I'm fairly certain an unrelated error (Maybe in do_search_selected()
?) is preventing the call from reaching 'return false' which causes the form to submit as normal.
Edit
Just saw you last comment. You can test this by running just the selector, an alert, and the override. If you're using AJAX asynchronously in that function you may need to set async
.
Also, add semicolons to the end of your statements!
Chris W.
Python was my first love, but Javascript is growing on me.
Updated on June 04, 2022Comments
-
Chris W. almost 2 years
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 thealert
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?