JulianJ
JulianJ

Reputation: 1309

How to detect which table was clicked with Jquery?

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

Answers (3)

Esko
Esko

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

Tomek Buszewski
Tomek Buszewski

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>');
});

Fiddle

With this approach it's not important if your button is above or under the <table></table> code.

Upvotes: 0

Satpal
Satpal

Reputation: 133453

You can use the relationship between the DOM elements. As table is immediately following sibling of anchor element, .next() function can be used to target it.

$('a').click(function() {
   $(this).next('table').find('> tbody > tr').append('<td>info,</td>');
});

Fiddle

Upvotes: 3

Related Questions