Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I find a parent of a dynamic table td?

Here’s some HTML code:

$("#MyTable").on('click', '.MakeNewTableRow', function() {
  var thisRow = $(this).closest("tr");
  thisRow.after("<tr><td>click me</td></tr>");
  thisRow.next().find("td:first").addClass('ShowTheTDValue');
});

$("#MyTable").on('click', '.ShowTheTDValue', function() {
  alert($(this).parent().find("td:first").text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='MyTable'>
  <tr>
    <td class='MakeNewTableRow'>whatever</td>
  </tr>
</table>

I’ll get a javascript error about how $(this).parent is not a defined function. I can understand how dynamically-created items aren’t part of the DOM and therefore I cannot access the previous table row with a parent() function, but surely there’s some way to get the data from the table row just above the one that gets created dynamically?

How would I do it? I just need to get the word "whatever" into a javascript variable.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You will want to use $(this).parent().prev().find("td:first").text()`.

By just using parent, you are getting the parent of the element being clicked on. But you actually want the element before the parent of the element being clicked on.

$("#MyTable").on('click', '.MakeNewTableRow', function() {
  var thisRow = $(this).closest("tr");
  thisRow.after("<tr><td>click me</td></tr>");
  thisRow.next().find("td:first").addClass('ShowTheTDValue');
});

$("#MyTable").on('click', '.ShowTheTDValue', function() {
  alert($(this).parent().prev().find("td:first").text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='MyTable'>
  <tr>
    <td class='MakeNewTableRow'>whatever</td>
  </tr>
</table>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading