Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get column header and row header on cell click

I already have the function working on selecting a cell, using this:

$('td').click(function(){
    //do things here
}

I want it get the text from the header of the column (this is within thead and then it's own th tag), and also get the row header, this is the left most column on the table and is also denoted under a th tag.

HTML:

<table>
<thead>
<tr>
    <th>Day/Time</th>
    <th>10:00</th>
    <th>11:00</th>
    <th>12:00</th>
</tr>
<tbody>
<tr>
    <th>Monday</th>
    <td>Cell data</td>
    <td>Cell data</td>
    <td>Cell data</td>
</tr>
<tr>
    <th>Tuesday</th>
    <td>Cell data</td>
    <td>Cell data</td>
    <td>Cell data</td>
</tr>
<tr>
    <th>Wednesday</th>
    <td>Cell data</td>
    <td>Cell data</td>
    <td>Cell data</td>
</tr>
</tbody>
</table>
like image 255
TheBritishBloke Avatar asked Feb 14 '14 11:02

TheBritishBloke


2 Answers

Here we go, exotic blend of jQuery and pure JS:

$('table').on('click', 'td', function(e) {  
    var time = e.delegateTarget.tHead.rows[0].cells[this.cellIndex],
        day  = this.parentNode.cells[0];

    alert([$(day).text(), $(time).text()]);
});

Demo: http://jsfiddle.net/fv3gZ/

I would recommend to delegate click events to the table, instead of binding click on each td, it would increase performance.

like image 75
dfsq Avatar answered Sep 26 '22 15:09

dfsq


As your html structure if you wanted to get header of corresponding cell you can use siblings Try this:

demo : http://jsfiddle.net/qsDn5/29/

  $('td').on('click',function() {
       var text = $( this ).siblings('th').text();
        alert(text);
    });
like image 32
Awlad Liton Avatar answered Sep 25 '22 15:09

Awlad Liton