Reputation: 1309
I have a page that contains multiple tables with unique id's that are populated with data from an ajax call. In the code below I am trying to figure out how to detect the closest table to which the button was clicked and only append new data to that table. I think this is possible with jquery's .closest() method but can't figure out how to do it? Here's a fiddle here Can anyone show me?
<table id="myTable1">
<tbody>
<tr>
<td>Info</td>
</tr>
</tbody>
</table>
Add data
<table id="myTable2">
<tbody>
<tr>
<td>Info</td>
</tr>
</tbody>
</table>
Add data The jquery
$(document).ready(function() {
$('a').click(function() {
$('#myTable1 > tbody > tr').append('<td>info,</td>');
});
});
Upvotes: 0
Views: 316
Reputation: 4207
The other answers are correct also but here is another approach using unobstrusive way of doing it using a data-attribute to tell which table to interact with:
$(document).ready(function() {
$('a').click(function() {
$("#" + $(this).data("table")).find('tbody > tr').append('<td>info,</td>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="javascript:void(0);" data-table="myTable1">Add data</a>
<table id="myTable1">
<tbody>
<tr>
<td>Info</td>
</tr>
</tbody>
</table>
<!----ANOTHE TABLE---->
<a href="javascript:void(0);" data-table="myTable2">Add data</a>
<table id="myTable2">
<tbody>
<tr>
<td>Info</td>
</tr>
</tbody>
</table>
Upvotes: 1
Reputation: 7955
You can wrap the table and the link in a div and then look inside.
$('a').click(function() {
$(this).parent().find('table > tbody > tr').append('<td>info,</td>');
});
With this approach it's not important if your button is above or under the <table></table>
code.
Upvotes: 0