Reputation: 117
I have a table, and in that table I have values with id="edit"
. Now, what I want is to get the header name of the corresponding column when I click on any of the cells. What I have so far, based on a previous question asked is:
$('body').on('click', 'td#edit', function() {
var th = $('this').closest('th').eq($('th').val());
alert(th); // returns [object Object]
.........................
}
Can you help me out with this?
HTML:
<table id="myTable" class="myTable">
<tbody>
<tr>
<th>Select</th>
<th>JobNo</th>
<th>Customer</th>
<th>JobDate</th>
<th>Warranty</th>
<th>RepairStatus</th>
<th>POP</th>
<th>DOA</th>
<th>Model</th>
<th>SN</th>
</tr>
<tr>
<td class="check">
<input type="checkbox" value="12345">
</td>
<td class="edit">
<b>12345</b>
</td>
<td class="edit">gdsgasdfasfasdfa</td>
<td class="edit">2011-01-21</td>
<td class="edit">TRUE</td>
<td class="edit">RP</td>
<td class="edit">FALSE</td>
<td class="edit">0</td>
<td class="edit">5152342</td>
<td class="edit">66665464</td>
</tr>
</tbody>
Upvotes: 3
Views: 29694
Reputation: 2060
For this markup
<table>
<tr class="header">
<th>Header One</th>
<th>Header Two</th>
<th>Header Three</th>
</tr>
<tr>
<td class="edit">One</td>
<td class="edit">Two</td>
<td class="edit">Three</td>
</tr>
<tr>
<td class="edit">One</td>
<td class="edit">Two</td>
<td class="edit">Three</td>
</tr>
</table>
You can use this jQuery code:
$(".mytable").on('click', 'td.edit', function(e) {
var index = $(this).index();
var table = $(this).closest('table');
console.log(table.find('.header th').eq(index).text()); // returns the header text
});
Fiddle here: http://jsfiddle.net/7qXm8/
Upvotes: 2
Reputation: 148140
The function closest() loop in ancestors up the DOM
tree and th is not parent of td so closest is not right option. First of all use class if you are having same id for more than one elements. Secondly use index() to find the corresponding th
of td
. For being specific assign id
to parent table so that the script does not operate on other tables / td
on page.
Html
<table id="tbl1" border="1">
<tr>
<th>heading 1</th>
<th>heading 2</th>
</tr>
<tr>
<td class="edit">row 1, cell 1</td>
<td class="edit">row 1, cell 2</td>
</tr>
<tr>
<td class="edit">row 2, cell 1</td>
<td class="edit">row 2, cell 2</td>
</tr>
</table>
Javascript
$('#tbl1').on('click', '.edit', function () {
var th = $('#tbl1 th').eq($(this).index());
alert(th.text()); // returns text of respective header
});
Upvotes: 13