I am trying to get the third text from the nearest <tr>
that contains only a specified text in one of the <td>
(in this case, "cat"), when clicked certain click events.
Below is my example table, and what I'm trying to get is, whenever "click1 or 2 or 3" is clicked, the third <td>
text from the closest/previous <tr>
that has "cat"
text.
<table class="animals">
<tr>
<td> cat </td>
<td> dog </td>
<td> tiger </td>
</tr>
<tr>
<td> dog-1 </td>
<td> dog-2 </td>
<td> dog-3 </td>
<td> <a href="#" class="drop">click1</a> </td>
</tr>
<tr>
<td> cat </td>
<td> mouse </td>
<td> horse </td>
</tr>
<tr>
<td> lion </td>
<td> zebra </td>
<td> camel </td>
<td> <a href="#" class="drop">click2</a> </td>
</tr>
<tr>
<td> goat </td>
<td> cow </td>
<td> sheep </td>
<td> <a href="#" class="drop">click3</a> </td>
</tr>
</table>
If "click1" is clicked, it should only get tiger from the closest(preceding) <tr>
. And if "click2", or "click3" is clicked, it should only get horse. My code is giving me both "tiger" and "horse" whichever one is clicked.
$('.drop').click(function() {
var val = $(this).closest('table').find('tr:contains("cat")').find('td:eq(2)').text();
alert(val);}
);
Any help to figure this out would be greatly appreciated.
$(this).closest('table').find('tr:contains("cat"):lt('+$(this).closest('tr').index()+'):last').find('td:eq(2)').text();
JSFiddle: https://jsfiddle.net/5S5Pn/3/