Reputation: 6394
What I am trying is to catch all the form submit events, get the url from the action attribute and use it to send the content of the form to that address using AJAX. So what I need is only one on submit event handler. However I quickly got in trouble as it seems to not be working in IE.
$(document).submit(function(e) {
alert('clicked');
e.preventDefault();
});
This is the code I use for cross-browser testing purpose. It works perfectly in Chrome, Firefox but not in IE. Am I not allowed to set an event listener on document?
Upvotes: 10
Views: 27706
Reputation: 237817
Have a look at the jQuery API:
The JavaScript submit event does not bubble in Internet Explorer. However, scripts that rely on event delegation with the submit event will work consistently across browsers as of jQuery 1.4, which has normalized the event's behavior. (api.jquery.com/submit)
The submit
event does not bubble in Internet Explorer, so the document
element will never be notified of submit
events. jQuery will normalise this for you, but only if you use event delegation. This is not difficult to do, and in fact may make your code nicer, if there is more complexity to it:
$(document).on('submit', 'form', function(e) {
alert('clicked');
e.preventDefault();
});
This keeps the advantages of binding to the document
(e.g. capturing events on elements that don't yet exist), while making it possible in IE. Note that this
, within the event handler, is now the form
element, not the document
.
Upvotes: 25
Reputation: 38079
What about:
$("form").submit(function(e) {
alert('clicked');
e.preventDefault();
});
Upvotes: 3
Reputation: 47657
Attach the listener to your forms
$("form").submit(function(e) {
alert('clicked');
e.preventDefault();
});
Upvotes: 3