user49126
user49126

Reputation: 1863

On function doesn't work where the live function did

I've read that the live function is deprecated and one should use the on method instead.

So I edited my code from

$('form').live('submit', function (event) {})

to

$('form').on('submit', function (event) {})

and it doesn't work anymore :-) I'm wondering why ?

BTW the form element is added dynamically.

Upvotes: 0

Views: 86

Answers (2)

billyonecan
billyonecan

Reputation: 20270

You need to attach the event handler to an element which exists in the DOM on page load:

$('body').on('submit', 'form', function(event) {
 ...
});

You should substitute body for an element which is closer to the form, this way the event only has to bubble up one level, thus increasing performance, for example:-

<div id="container">
  <form>
    ...
  </form>
</div>

Then you would use:

$('#container').on('submit', 'form', function(event) {
  ...
});

All of this information can be found in the documentation

Upvotes: 2

Claudio Redi
Claudio Redi

Reputation: 68440

Use this instead

$('body').on('submit', 'form', function (event) {})

Check section Direct and delegated events on the jquery documentation for on method

Upvotes: 2

Related Questions