-1

I read that .live() has been deprecated, and that I should use .on instead. But .on doesn't seem to be working for elements added to the DOM.

My script adds a table with any number of text boxes (input type="text"), and I want to run some script when the content in any of those text boxes changes.

Here's part of my code. vendorsPopUp references the div that contains my table.

$('input', vendorsPopUp).on('change', function (e) {
    alert($(this).attr('class'));
});

But this code does not run when the content in a text box changes.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
  • you call on() on the table or body or div, not inputs, which have no sub-elements. on() uses a parent container that watches any element under it for the event, not just the few elements found at time of binding; thats why it needs the extra selector argument. right now, you use on() in legacy mode. – dandavis Sep 30 '14 at 22:16
  • 1
    Duplicate of many other questions. I will go find a duplicate now. – jfriend00 Sep 30 '14 at 22:18
  • 1
    @dandavis not legacy mode, in directly binding mode. there's nothing legacy about binding directly to an element. – Kevin B Sep 30 '14 at 22:20
  • 1
    Someone voted me down because the question has already been asked? I did a number of searches. I'm sorry, I just wasn't finding the right data. If it's closed as a duplicate, that's fine. But the person who downvoted just seems like a jerk. – Jonathan Wood Sep 30 '14 at 22:25
  • legacy is perhaps pejorative, but there's no advantage to on() without delegation, and it might be misleading to coders expecting a sub-selector. without delegation, you might as well use a more semantic .change() handler. – dandavis Sep 30 '14 at 22:25
  • @dandavis: I was told to use `.on` instead of `.click()`, etc. Are you saying you don't use `.on` for static elements? – Jonathan Wood Sep 30 '14 at 22:28
  • @JonathanWood: both work, but .click() is more readable and faster to execute if you don't need to hit future elements. there's nothing wrong with on(), it's a powerful new feature, but just because you get a new hammer doesn't mean you have to use it on push pins... – dandavis Sep 30 '14 at 22:29
  • You know, because `.click` doesn't forward directly to `.on('click'`. `` – Kevin B Oct 01 '14 at 20:37

1 Answers1

0

It should be like this

$(vendorsPopUp).on('change', 'input', function (e) {
   alert($(this).attr('class'));
});
Bojan Petkovski
  • 6,835
  • 1
  • 25
  • 34
  • 1
    This is the right answer. It's clear and concise, and it has the code I need. That's fine if the question is closed as a duplicate. But I don't know why some people are so bent on downvoting. Especially those who do so without a comment. – Jonathan Wood Sep 30 '14 at 22:26