Home > Enterprise >  jQuery event delegation is not retrieving table contents
jQuery event delegation is not retrieving table contents

Time:11-09

Edit to include ultimate goal: When I click on a table row, I'd ultimately like to retrieve the contents of each cell on that row. In this example, I'm simply trying to get the contents of any one cell (the first?) within the row that is clicked. Once I get one cell, I'm sure I can get the others.

I have successfully used event delegation with dynamic elements before, but I can't understand why it's not working with my table - specifically with tables.

The event delegation works, it's not the problem (click is detected, alert is triggered). References to the basics of event delegation are not going to help, because that's not where the problem lies.

I think the problem is with the function associated with the event. I am basing the function on this QA about retrieving the contents of a table, but I must be applying the solution incorrectly as a function of even delegation: Get the contents of a table row with a button click

jQuery with event delegation:

$('#loadQA').on('click', 'table', function () { // PROBLEM ISN'T HERE

    // THE PROBLEM MUST BE IN HERE SOMEWHERE
    var $row = $(this).closest("tr");
    var $text = $row.find("td").text();
    alert($text);

})

HTML containing dynamic table:

<div id="loadQA"> <!-- THIS ELEMENT IS STATIC -->

<table class='table table-dark table-hover table-borderless' id='qaDAT'> <!-- DYNAMIC TABLE -->
     <thead class='darker text-orange' id='qaHead'>
          <tr>
               <th scope='col'>#</th>
               <th scope='col'>Question</th>
               <th scope='col'>Answer</th>
          </tr>
     </thead>
     <tbody>
          <tr id='rowDAT'>
               <th class='colDAT' scope='row'>qaID</th>
               <td class='colDAT'>question</td>
               <td class='colDAT'>answer</td>
          </tr>
     </tbdoy>
</table>

</div>

Summary for clarity: I am trying to marry jQuery event delegation with the linked QA solution for static tables. I can achieve these independently, but not when trying to combine the techniques. Where did I go wrong?

CodePudding user response:

You should delegate to the table cells, not the whole table.

From there you can navigate to the row with .closest(), then to the cells in the row.

$('#loadQA').on('click', 'td,th', function () {
    var $row = $(this).closest("tr");
    $row.find("td").each(function() {
        console.log($(this).text());
    });
})
  • Related