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.
>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>