1

How can I find the head line each table cell's "visual location" using jQuery?
For example, if click "this" or "click this" cell, get "second" cell's text.

table,
th,
td {
  border: 1px solid black;
}
<table class="table table-bordered">
  <thead>
    <tr>
      <th>third</th>
      <th colspan="2">second</th>
      <th>third</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td rowspan="2"></td>
      <td>this</td>
      <td>this</td>
      <td></td>
    </tr>
    <tr>
      <td rowspan="2">this</td>
      <td>click this</td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td>this</td>
      <td></td>
    </tr>
  </tbody>
</table>

View on JSFiddle

showdev
  • 28,454
  • 37
  • 55
  • 73
polu
  • 41
  • 1
  • 6
  • 2
    Hope this helps you http://stackoverflow.com/questions/3523770/how-can-i-get-the-corresponding-table-header-th-from-a-table-cell-td – Geeky Oct 07 '16 at 22:57
  • thank you! I found a working solution: https://jsfiddle.net/hssvupe8/1/ :) – polu Oct 07 '16 at 23:38

1 Answers1

-1

Here is the solution

$(document).ready(function(){
  $('.table td').bind('click',ClickMe)
});
function ClickMe(event){
  var targetObject=event.target;
  var $targetObject=$(targetObject);
  var index=$targetObject.index();
 var $indexObject=$targetObject.closest('table').find('th').eq(index);
  alert($indexObject.html());
}
table,
th,
td {
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table class="table table-bordered">
  <thead>
    <tr>
      <th>third</th>
      <th colspan="2">second</th>
      <th>third</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td rowspan="2"></td>
      <td>this</td>
      <td>this</td>
      <td></td>
    </tr>
    <tr>
      <td rowspan="2">this</td>
      <td>click this</td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td>this</td>
      <td></td>
    </tr>
  </tbody>
</table>

Hope this helps

Geeky
  • 7,420
  • 2
  • 24
  • 50
  • 1
    Good start, but this doesn't seem to take `rowspan` or `colspan` into account. For example, when I click the first `` under the "third" header, I get "undefined"; some of the cells under the "second" header output "third". – showdev Oct 07 '16 at 23:06
  • i found a working solution: http://stackoverflow.com/a/37312894/4884098 – polu Oct 07 '16 at 23:41