jQuery 1.7 .on() and Dynamic Form Catching

560 Views Asked by At

I'm having a problem with jQuery 1.7's latest on() function. I'm moving all of my existing live() calls to the new on() function.

In the past I used live() whenever I created a new element or appended some markup from AJAX.

With jQuery 1.7 If I append form markup returned via AJAX and try to use e.preventDefault or return false to stop it from submitting (to validate it for example) — the form is submitted as normal.

$(document).on('submit', 'form', function(e) {
    alert('You tried to submit the form');
    e.preventDefault();
});
2

There are 2 best solutions below

0
On BEST ANSWER

This has been confirmed as a jQuery bug in 1.7.1, to be fixed in 1.7.2: http://bugs.jquery.com/ticket/11145

My original code is correct (for dynamic DOM elements). Adam Rackis' code is correct for existing DOM elements.

2
On

Your code is perfectly valid.

DEMO

If you post some more code we might be able to take a look and see if you have some other problem


But assuming this form is present when the page is rendered, I would just do this:

$("form").on('submit', function(e) {
    alert('You tried to submit the form');
    e.preventDefault();
});

(I'm assuming your page is rendered with the form already present)