Home > database >  Retrieve text value from the first row in the same column by class name
Retrieve text value from the first row in the same column by class name

Time:04-08

I have a table which will only ever have three rows. There is an image which is an anchor tag in the third row and from the click event of this anchor tag I want to retrieve the text value from the first row in the same column by the class name of thisEventName.

<table id="tblTimedPathwayEvents">
    <tbody>
        <tr>
            <td>Event</td>
            <td >)Event #1</td>
            <td >)Event #2</td>
            <td >)Event #3</td>
        </tr>
        <tr>
            <td>Target Day(s)</td>
            <td>2</td>
            <td>3</td>
            <td>28</td>
        </tr>
        <tr>
            <td>Performed Day</td>
            <td><a  href="#"><img src="http://localhost:55223//graphics/pencil-square.jpg" title="Edit"></a></td>
            <td><a  href="#"><img src="http://localhost:55223//graphics/pencil-square.jpg" title="Edit"></a></td>
            <td><a  href="#"><img src="http://localhost:55223//graphics/pencil-square.jpg" title="Edit"></a></td>
        </tr>
    </tbody>
</table>

I've tried things like this but to no avail

$(this).closest('td').find('.thisEventName').text();

CodePudding user response:

You can use .index() on the parent td, which will give its relative position within its parent (ie will give the column).

var idx = $(this).closest("td").index();

Then you can get the same column's td from the first row

$(this).closest("tbody").find("tr td").eq(idx)

Giving updated snippet:

$(".performedDayLink").click(function() {
  var idx = $(this).closest("td").index();
  var txt = $(this).closest("tbody").find("tr td").eq(idx).text();
  $("#out").text(txt);
  return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tblTimedPathwayEvents">
  <tbody>
    <tr>
      <td>Event</td>
      <td >)Event #1</td>
      <td >)Event #2</td>
      <td >)Event #3</td>
    </tr>
    <tr>
      <td>Target Day(s)</td>
      <td>2</td>
      <td>3</td>
      <td>28</td>
    </tr>
    <tr>
      <td>Performed Day</td>
      <td>
        <a  href="#">EDIT 1</a>
      </td>
      <td>
        <a  href="#">EDIT 2</a>
      </td>
      <td>
        <a  href="#">EDIT 3</a>
      </td>
    </tr>
  </tbody>
</table>
<hr/>
<div id="out"></div>

  • Related