Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 1s in the above table), it should pick it up and return 1.

like image 693
Muhammad Zeeshan Avatar asked Dec 24 '10 06:12

Muhammad Zeeshan


People also ask

How to know which row is clicked in table JAVASCRIPT?

You can use object. rowIndex property which has an index starting at 0.

How do you know which element is clicking?

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.

How do I find row ID in a table?

var table = document. getElementById("tableId"); var rowIndex = document. getElementById("b").

How can get row number in HTML table using jquery?

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


1 Answers

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); }); 
like image 181
Ken Redler Avatar answered Sep 20 '22 12:09

Ken Redler