Reputation: 111
There is my issue.
I have a simple table like this (for the example) :
$('#tab tbody tr td').on('click', function() {
var val = $(this).parent().find('table tbody tr th').text();
console.log(val);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tab">
<thead>
<tr>
<th>
Test 1
</th>
<th>
Test 2
</th>
<th>
Test 3
</th>
<th>
Test 4
</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
<tr>
<td>E</td>
<td>F</td>
<td>G</td>
<td>H</td>
</tr>
</tbody>
</table>
And I am trying to console.log(..)
the name of the column while i am clicking a <td>
element.
I think it may be a simple solution but i can't find it.
Thanks in advance
Upvotes: 0
Views: 862
Reputation: 28522
You can use :eq()
& index()
to achieve this.
Demo Code :
$('#tab tbody tr td').on('click', function() {
var val = $(this).index(); //get index no of td
console.log($("thead th:eq(" + val + ")").text().trim()); //get th value
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tab">
<thead>
<tr>
<th>
Test 1
</th>
<th>
Test 2
</th>
<th>
Test 3
</th>
<th>
Test 4
</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
<tr>
<td>E</td>
<td>F</td>
<td>G</td>
<td>H</td>
</tr>
</tbody>
</table>
Upvotes: 3