TheBritishBloke
TheBritishBloke

Reputation: 169

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>

Upvotes: 7

Views: 12697

Answers (3)

A.Muqtadir
A.Muqtadir

Reputation: 71

You can try this:

var td = document.getElementsByTagName("td"),
titles = document.getElementsByTagName("th")
for (var i = 0; i < td.length; i++) {
  td[i].addEventListener("click", function () {
    alert(titles[this.cellIndex].innerHTML);
  }, false);
}

Upvotes: 1

dfsq
dfsq

Reputation: 193271

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.

Upvotes: 9

Awlad Liton
Awlad Liton

Reputation: 9351

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

Upvotes: 1

Related Questions