Get column header and row header on cell click

10,827

Solution 1

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.

Solution 2

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);
    });
Share:
10,827
TheBritishBloke
Author by

TheBritishBloke

Updated on June 14, 2022

Comments

  • TheBritishBloke
    TheBritishBloke almost 2 years

    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>