I load some html using AJAX, this works fine, one of the bits that loads is a contact form which I am trying to intercept the submit event using
$(document).ready(function() {
$('contact_form').submit(function() {
return false;
});
});
The above javascript is loaded with the initial page load.
However, when I visit the page and submit the form it follows its default path and follows the regular submit (which works but it is my non-javascript compatability route that I want most users not to follow). I have tried testing .click() events on bits of the page that are initially loaded and similar bits that are loaded using AJAX, the result being that only the elements that were initially loaded with the page execute the .click() event.
I’m guessing that it is the fact that I load the jQuery code before adding the elements to the DOM (I have some <script> tags that load with the initial page load) and this is not regestering the listeners propperly (wild guess, I actually don’t really have a clue).
Am I correct in my assumption? And what is the best fix?
First of all
contact_formisn’t a valid selector, as it’s looking for a<contact_form>element. It should be#contact_formto select by id, or.contact_formto select by class.Secondly your assumption about the event handlers is correct, the shortcut event handlers (
click,submitetc.) only work on elements available in the DOM on page load.If the element is appended to the DOM after page load (eg. via AJAX) you need to use
delegate()oron()(in jQ1.7+) to add events to that element:Or:
I have used
bodyas the parent selector here, but you should use the closest static element (that is one that is available in the DOM on page load) to the one you are placing the event on.