0

I am using the following listener:

   $('#datatable .Answer input:radio').on('change', function() {
        alert('Radio Button');

    });

And I add radio button dynamically to this table '#datatable' as follows:

   $(this).html('<input type="radio" class="Answer" name="correct"/>');

where this is the td element in which radio button should be added. Why doesn't the listener work on new elements?

Sohaib
  • 4,058
  • 7
  • 35
  • 66
  • *"Why doesn't the listener work on new elements?"* You can find an answer to that in the [documentation](http://api.jquery.com/on/): *"Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to `.on()`."* – Felix Kling Jul 07 '13 at 13:35

1 Answers1

2

Why doesn't the listener work on new elements?

Because you should subscribe to the change event like this:

$('#datatable .Answer').on('change', 'input:radio', function() {
    alert('Radio Button');

});

Notice how the 'input:radio' selector is moved to the .on() function in order to subscribe to the event in a lively manner.

Darin Dimitrov
  • 960,118
  • 257
  • 3,196
  • 2,876