I have a table like the following:
<table> <tr> <td>1</td><td>1</td><td>1</td> </tr> <tr> <td>2</td><td>2</td><td>2</td> </tr> <tr> <td>3</td><td>3</td><td>3</td> </tr> </table>
When a user clicks on the table, how can I get the index of this row (tr
element)?
For example, when I click on the first tr
(with 1
s in the above table), it should pick it up and return 1
.
You can use object. rowIndex property which has an index starting at 0.
To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked.
var table = document. getElementById("tableId"); var rowIndex = document. getElementById("b").
You can use the Core/index function in a given context, for example you can check the index of the TD in it's parent TR to get the column number, and you can check the TR index on the Table, to get the row number: $('td'). click(function(){ var col = $(this). parent().
This would get you the index of the clicked row, starting with one:
$('#thetable').find('tr').click( function(){ alert('You clicked row '+ ($(this).index()+1) ); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="thetable"> <tr> <td>1</td><td>1</td><td>1</td> </tr> <tr> <td>2</td><td>2</td><td>2</td> </tr> <tr> <td>3</td><td>3</td><td>3</td> </tr> </table>
If you want to return the number stored in that first cell of each row:
$('#thetable').find('tr').click( function(){ var row = $(this).find('td:first').text(); alert('You clicked ' + row); });
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