vulkoingim vulkoingim - 14 days ago 9
jQuery Question

jQuery get table header name of clicked cell with id

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>



Answer

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.

Live Demo

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
});