0

I have a table with data and a function to help me get values from rows:

    function getRow () { 
        $('#mytable').find('tr').click( function(){
              let  fname = $(this).find('td:eq(4)').text();
                  let start = $(this).find('td:eq(5)').text();
                  let end = $(this).find('td:eq(6)').text();
.......ajax method () etc
................
    }

So far, it has been working perfectly and fetching me the correct data. I had another function elsewhere in the page, where clicking on some links would fetch some data from the server and reload the page to display the new data. Everything was working like clockwork.

Now, I decided that when re-displaying fresh data, instead of reloading the page, it's better to refresh the #mytable div. Indeed, it worked, but alas it spoiled the first function. So basically the function below has introduced a bug elsewhere in the page, and I'm not sure why or how to fix it. It's as if the div refresh has completely disabled the event handler. Any ideas?

$(document).ready(function() {
$(".key").click(function(event) {


        event.preventDefault();
        var word = event.target.innerHTML;



        $.ajax({
            url: '.../',


            data: {

                action : "key",
                keyword: word
            },
            type: 'get',
            success: function(data){

                $('#mytable').load("/.../../..." +  ' #ytable');

                },
            error: function(e){
                console.log(e);}
        });

    });
});
A_W
  • 53
  • 1
  • 7
  • A click handler (as you've used it) attaches an event to any elements that satisfy the selector **at the time the line of code is run**. Therefore if you wrote an event handler, *then* added 10 `tr` elements, they won't have events because they weren't in the DOM at the time you attached the event. You're looking for **Event Delegation**. Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Tyler Roper Aug 06 '18 at 04:21
  • Wow. Many thanks. I appreciate the prompt reply. – A_W Aug 06 '18 at 04:25
  • 1
    Not a problem. The event delegation in your case would look something like this: `$('#mytable').on("click", "tr", function() { ... })` – Tyler Roper Aug 06 '18 at 04:27
  • It works! Many, many thanks for your help! :) – A_W Aug 06 '18 at 14:50

0 Answers0