Brian Bruman
Brian Bruman

Reputation: 913

Getting Closest TR with jQuery when clicking on an "OnClick" function inside a TD?

Is this possible? Is the fact I am using an inline onclick function deterring from getting the TR row?

My Table Row looks like this:

<tr role="row" class="odd"><td><a class="masterskutd" id="mastersku_FL538-J"
      onclick="editMasterSKU('FL538-J');return false;">FL538-J</a></tr>

In an external JS file functions.js I am trying things such as this

function editMasterSKU(SKU) {
    var tr = $(this).closest('tr');
    $(tr).addClass('clicked');
    // var tr = $(this).parents('tr');
    console.log(tr);

Nothing I do seems to catch the TR that the function was clicked upon, the console.log only brings back w.fn.init(0) (not entirely sure what this means) with a length of 0, and it is not adding the class to the row.

How can I get the TR in a jQuery variable when clicking on my onclick function inside the td / a?

Upvotes: 0

Views: 2537

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337610

The issue is because functions called from inline event attributes do not run under the scope of the element which raised the event. They instead run under the scope of the window, hence this is not what you expect it to be.

To fix this you can pass this as an argument to the function from the onclick:

function editMasterSKU(a, SKU) {
  var tr = $(a).closest('tr');
  $(tr).addClass('clicked');
}
.clicked {
  color: #C00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr role="row" class="odd">
    <td>
      <a class="masterskutd" id="mastersku_FL538-J" onclick="editMasterSKU(this, 'FL538-J');return false;">FL538-J</a>
    </td>
  </tr>
</table>

However it's worth noting that you should not be using inline event attributes at all. Use unobtrusive event handlers instead. As you're already including jQuery in the page it can be done like this:

jQuery(function($) {
  $('.masterskutd').on('click', function(e) {
    e.preventDefault();
    var $tr = $(this).closest('tr');
    $tr.addClass('clicked');
    console.log($(this).data('sku'));
  });
})
.clicked a {
  color: #C00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr role="row" class="odd">
    <td>
      <a class="masterskutd" id="mastersku_FL538-J" data-SKU="FL538-J" href="#">FL538-J</a>
    </td>
  </tr>
</table>

Note the use of the data attribute to store the custom meta data in the element itself, and also the addition of the href attribute, which is required for the HTML to be valid.

Upvotes: 2

Related Questions