get the column header on cell click

Viewed 1035

I want to get the column header of the table on cell click.I have tried as below.Now all the th value is displaying.now to get the relavent th value.

$('td').click(function() {
    var txt = $(this).text();
 var label=$(this).closest('tr').find('.label').text();
 var header=$(this).closest('table').find('th').text();
    console.log(txt + ':' +label + ':'+header);
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead id="thead">
  <th></th>
  <th>Week 1 </th>
   <th>Week 2 </th>
   <th>Week 3 </th>
   <th>Week 4 </th></thead>
  <tbody id="tbody"><tr><td class="label">test1</td><td>5</td><td>2</td><td>7</td><td>1</td></tr><tr><td class="label">test2</td><td>9</td><td>15</td><td>12</td><td>4</td></tr><tr><td class="label">test3</td><td>32</td><td>12</td><td>23</td><td>28</td></tr><tr><td class="label">test4</td><td>1</td><td>0</td><td>0</td><td>0</td></tr></tbody>
  <tbody id="tfooter"><tr><td>Total</td><td>145</td><td>120</td><td>157</td><td>162</td></tr></tbody>
</table>

1 Answers

To make this work you need to get the th which matches the index of the clicked td in the row. To do that use index() and eq(), like this:

$('td').click(function() {
  let $cell = $(this);
  let txt = $cell.text();
  let label = $cell.closest('tr').find('.label').text();
  let header = $cell.closest('table').find('th').eq($cell.index()).text();
  console.log(txt + ':' + label + ':' + header);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead id="thead">
    <th></th>
    <th>Week 1 </th>
    <th>Week 2 </th>
    <th>Week 3 </th>
    <th>Week 4 </th>
  </thead>
  <tbody id="tbody">
    <tr>
      <td class="label">test1</td>
      <td>5</td>
      <td>2</td>
      <td>7</td>
      <td>1</td>
    </tr>
    <tr>
      <td class="label">test2</td>
      <td>9</td>
      <td>15</td>
      <td>12</td>
      <td>4</td>
    </tr>
    <tr>
      <td class="label">test3</td>
      <td>32</td>
      <td>12</td>
      <td>23</td>
      <td>28</td>
    </tr>
    <tr>
      <td class="label">test4</td>
      <td>1</td>
      <td>0</td>
      <td>0</td>
      <td>0</td>
    </tr>
  </tbody>
  <tbody id="tfooter">
    <tr>
      <td>Total</td>
      <td>145</td>
      <td>120</td>
      <td>157</td>
      <td>162</td>
    </tr>
  </tbody>
</table>

Related