I have a table like the following:
<table>
<tr>
<td>1</td><td>1</td><td><a href="1" id='1' class'alert'>1</a></td>
</tr>
<tr>
<td>2</td><td>2</td><td><a href="2" id='2' class'alert'>2</a></td>
</tr>
<tr>
<td>3</td><td>3</td><td><a href="3" id='3' class'alert'>3</a></td>
</tr>
</table>
When a user clicks on the <a>, how can I get the index of this row (tr element)?
For example, when I click on the first <a> it should pick it up and return <td>1</td><td>1</td><td><a href="1" id='1' class'alert'>1</a></td>.
You can get index by using index()
$('table a').click(function(e) {
e.preventDefault(); // prevent default click action
alert($(this)
.closest('tr') // get the tr
.index() + 1 // get index based on siblings , add 1 since index start from 0
);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table>
<tr>
<td>1</td>
<td>1</td>
<td><a href="1" id='1' class 'alert'>1</a>
</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td><a href="2" id='2' class 'alert'>2</a>
</td>
</tr>
<tr>
<td>3</td>
<td>3</td>
<td><a href="3" id='3' class 'alert'>3</a>
</td>
</tr>
</table>
td then use prev()
$('table a').click(function(e) {
e.preventDefault(); // prevent default click action
alert($(this)
.parent() // get parent td
.prev('td') // get previous sibling
.text() // get text
);
// or get first column by
// $(this).closest('tr').children('td').eq(0).text()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table>
<tr>
<td>1</td>
<td>1</td>
<td><a href="1" id='1' class 'alert'>1</a>
</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td><a href="2" id='2' class 'alert'>2</a>
</td>
</tr>
<tr>
<td>3</td>
<td>3</td>
<td><a href="3" id='3' class 'alert'>3</a>
</td>
</tr>
</table>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With