Please see the fiddle. When I click the cell, I can get the value and the column name. I wonder how can I get the row and column index instead? Following is the js code,
<script type="text/javascript">
$(document).ready(function(){
$('#example tbody').on( 'click', 'td', function () {
alert('Data:'+$(this).html().trim());
alert('Row:'+$(this).parent().find('td').html().trim());
alert('Column:'+$('#example thead tr th').eq($(this).index()).html().trim());
});
});
</script>
Another Native JS way to do this is using TableData properties that can be found when using table elements. For example, cellIndex
will return the column index of a td
element and rowIndex
will return the index of a tr
element. These two properties will simplify our code by a ton, shown on the following code.
const cells = document.querySelectorAll('td');
cells.forEach(cell => {
cell.addEventListener('click', () =>
console.log("Row index: " + cell.closest('tr').rowIndex + " | Column index: " + cell.cellIndex));
});
<table>
<tr>
<td>0:0</td>
<td>0:1</td>
<td>0:2</td>
<td>0:3</td>
</tr>
<tr>
<td>1:0</td>
<td>1:1</td>
<td>1:2</td>
<td>1:3</td>
</tr>
<tr>
<td>2:0</td>
<td>2:1</td>
<td>2:2</td>
<td>2:3</td>
</tr>
</table>
No need for jQuery, you can achieve it with native JS:
const table = document.querySelector('table');
const rows = document.querySelectorAll('tr');
const rowsArray = Array.from(rows);
table.addEventListener('click', (event) => {
const rowIndex = rowsArray.findIndex(row => row.contains(event.target));
const columns = Array.from(rowsArray[rowIndex].querySelectorAll('td'));
const columnIndex = columns.findIndex(column => column == event.target);
console.log(rowIndex, columnIndex)
})
The best probably would be to use closest
here:
For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
<script type="text/javascript">
$(document).ready(function(){
$('#example tbody').on( 'click', 'td', function () {
alert('Row ' + $(this).closest("tr").index());
alert('Column ' + $(this).closest("td").index());
});
});
</script>
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