How to get the value from a cell when table row is clicked

Viewed 36

I am trying to get the href value from the cell with the class editlink. This is what I have tried but I'm getting undefined in the alert.

<table id="table_1">
  <thead></thead>
  <tbody>
    <tr>
      <td>sometext</td>
      <td class="editlink"><a href="/linkid444">edit</a></td>
    </tr>
    <tr>
      <td>sometext2</td>
      <td class="editlink"><a href="/linkid555">edit</a></td>
    </tr>
  </tbody>
  <tfoot></tfoot>
</table>
$(document).ready(function() {
  $("#table_1").delegate("tr", "click", function() {
    var linkdata = $(this).closest('tr').find('.editlink').attr("href");
    alert(linkdata);
  });
});
1 Answers

Firstly note that delegate() has been deprecated. Instead, use the delegated signature of the on() method. This may also mean that you need to upgrade the version of jQuery you're using.

As for the issue you have, it's because .editlink is the td. The href property is on the a element, so the selector needs to be .editlink a. Also, closest('tr') is redundant, as the event handler is already bound to the tr. Try this:

$(document).ready(function() {
  $("#table_1").on('click', "tr", function() {
    var linkdata = $(this).find('.editlink a').attr("href");
    console.log(linkdata);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table_1">
  <thead></thead>
  <tbody>
    <tr>
      <td>sometext</td>
      <td class="editlink"><a href="/linkid444">edit</a></td>
    </tr>
    <tr>
      <td>sometext2</td>
      <td class="editlink"><a href="/linkid555">edit</a></td>
    </tr>
  </tbody>
  <tfoot></tfoot>
</table>

Related