1

I have a php employee directory website that lists all our employees in a table (connected to mysql), and you are able to click each employee to open up their details in another div.

$('.emptab').click(function(event) {
    var status = $(this).attr('id');
    $("#empview").load("employee.php", {'data': datastring, 'current': status});
});

I originally had the above code, but needed to be able to attach events to dynamic elements, so I changed to the following code:

$('tbody').on('click', 'tr.emptab', function() {
    var status = $(this).attr('id');
    $("#employeedetails").load("employee.php", {'data': datastring, 'current': status});
});

I did it that way as I read in another question (In jQuery, how to attach events to dynamic html elements?) that you can use that format to attach events to dynamic elements. Just to clarify, this code continues to work with the initial page, but fails after the search filter is used.

My dynamic elements comes from a filter/search function I have that will change the list of employees based on a search text box which changes the list of employees based on a filter.php document I created.

$('#search').on('input propertychange paste', function() {
    var string = $('#search').val();
    $("#employeelist").load("filter.php", {'data': datastring, 'search': string});
});

However, when those elements are created from that php file, I am unable to access the elements through my jquery, I'm not sure what I'm doing wrong. There were about 4 other questions I saw where the answer was to use the jquery on function, which I've tried with no success.

Thanks for your time.

user163362
  • 13
  • 2

1 Answers1

0

You can use following code for this

$(document).on('click', '.emptab', function() {
    var status = $(this).attr('id');
    $("#employeedetails").load("employee.php", {'data': datastring, 'current': status});
});
Super User
  • 9,448
  • 3
  • 31
  • 47
  • Hey thanks, that worked. Just wondering, why did it have to be document and not something like body or table, etc.? – user163362 Aug 29 '17 at 07:40
  • It's Event Delegation, which allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future. May be your tbody element has created dynamically, that's why it's working – Super User Aug 29 '17 at 07:43
  • @user163362 it didn’t have to, any already existing ancestor element of the future elements will do. – CBroe Aug 29 '17 at 07:43
  • @CBroe OP are using `tbody` element. May be it's generating dynamically – Super User Aug 29 '17 at 07:46