Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell which row number is clicked in a href in a table?

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

like image 894
Tlaloc-ES Avatar asked Jan 31 '26 02:01

Tlaloc-ES


1 Answers

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>


If you want to get number in 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>
like image 191
Pranav C Balan Avatar answered Feb 02 '26 17:02

Pranav C Balan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!