1

I create dynamic content via jQuery that looks like:

$('#usersList tbody').append(' \
<tr id="user_4242" class="highlight-tr"> \
    <td class="users-list-name">Dan</td> \
    <td class="users-list-edit" data-userid="{{ $user->id }}" data-toggle="modal" data-target="#userEditModal"> \
        <button class="btn btn-default btn-sm edit-user-btn"><i class="glyphicon glyphicon-edit"></i> Edit</button> \
    </td> \
</tr> \
');

Then, I try accessing the content in ".users-list-name" with:

$('.users-list-edit', '#usersList').on('click', function () {
    var name        = $(this).parent().find('.users-list-name').text();
    console.log(name) // dynamic content not working here
});

#usersList is the id of the table.

That click function works for the data that was already there on page load.

How can I access data in this dynamic appended content?

Dan P.
  • 1,171
  • 2
  • 18
  • 44
  • You are correct, thanks. BTW is there any post about calling JavaScript method(s) on the content appended by AJAX call? – MaxZoom Jan 26 '15 at 02:53

3 Answers3

2

You need to add the listener on the element that already exists, and then wait for the bobble event to hit it. Try below:

$(document).on('click', '.users-list-edit', function () {
  var name = $(this).parent().find('.users-list-name').text();
});
MaxZoom
  • 6,949
  • 5
  • 24
  • 41
1

you binded the Javascript Event Handler before append those code(event is binded if the target were exist), so that's why it didn't work.

in this case you should bind on the parent class for handling event of its child.

$('#usersList').on('click','.users-list-edit', function () {
    var name = $(this).parent().find('.users-list-name').text();
});

the code over there mean : when you click on '.user-list-edit' class and it's child of userList ID: the event handler function (callback) will be triggered.

Kai
  • 1,744
  • 15
  • 25
0

Try this:

$('#usersList').delegate('.users-list-edit', 'click', function(){
  var name = $(this).parent().find('.users-list-name').text();
});

The function it's being declared before the content exists, thats why you can't access it, you need to use a "delegate" function assigned to the parent and when the event occurs, it will delegate it to the selector you specify, and in that moment the DOM object already exists.

ivillamil
  • 98
  • 1
  • 6
  • from the docs: `As of jQuery 1.7, .delegate() has been superseded by the .on() method.` – charlietfl Jan 26 '15 at 02:49
  • You're completely right, I looked into the source code and it only returns the "on" event with the correct params, thanks for pointing it. – ivillamil Jan 26 '15 at 03:01
  • if you like looking into source, will like this tool http://james.padolsey.com/jquery/#v=1.10.2&fn=jQuery.fn.delegate – charlietfl Jan 26 '15 at 03:03