2

Possible Duplicate:
jQuery 1.7 - Turning live() into on()

I used to love the .live() function that jQuery had. You would add it and voila, any future elements that matched the identifier would have that function.

Then it got deprecated and it was advised to use .on(). But it doesn't work. Below is my code that is placed in $(document).ready().

This works

$('#membership_number').live('change',function(e) {
    alert("VALUE CHANGED");
});

This doesn't

$('#membership_number').on('change',function(e) {
    alert("VALUE CHANGED");
});

Is there another way to achieve the same effect as .live() or am I just not using .on() correctly?

Community
  • 1
  • 1
Bird87 ZA
  • 2,313
  • 8
  • 36
  • 69

4 Answers4

5

You have to subscripe the event to parent item and give selector to which you want to bind. If you do not want to give parent you can use document. Read more about on here

$(document).on('change', '#membership_number',function(e) {
    alert("VALUE CHANGED");
});

OR

$('#parentId').on('change', '#membership_number',function(e) {
    alert("VALUE CHANGED");
});
Adil
  • 146,340
  • 25
  • 209
  • 204
2

When handling dynamic elements in jQuery 1.7 +, you're using the on selector. It expects the event to be bound to a static element that is ready and available at page load, so the event can properly bubble up the chain and fire when the parent element is found.

$(document).on('change', '#membership_number', function(e){
    alert("VALUE CHANGED");
});
Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110
2

You need to use a parent element to attach the handler. E.g. the document.

$(document).on('change', '#membership_number', function(e) {
    alert("VALUE CHANGED");
});
Prinzhorn
  • 22,120
  • 7
  • 61
  • 65
2

You need to bind .on() at an ancestor element due to the way in which the event bubbles up until it matches the selector. This can be anything in the DOM that is an ancestor of the element you want the event(s) bound to.

You can of course use the ultimate ancestor, the document. For example:

$(document).on('change', '#membership_number', function(){});

.live() actually did this behind the scenes by binding an event on the document which was then filtered on the correct element. It is more efficient and practical to use an element as local as possible to the one you want an event on. For example if I wanted a click event on <li> elements where some <li> are added dynamically, I would bind the event to the parent <ul> and filter on the <li> like so:

$('ul').on('click', 'li', function(){});

This is also more efficient than binding a separate click event on each <li>.

andyb
  • 43,435
  • 12
  • 121
  • 150