Jon Story
Jon Story

Reputation: 3061

Retrieve parent element ID on focus out

I'm trying to retrieve the TR element's ID, whenever the user removes focus from that TR. Triggering the event is easy enough, but I can't work out how best to retrieve the ID

$(".row-identifying-class").focusout(function (e) {
    var rowID = e.target.id; // Returns the ID of the TD/input/label etc the user last clicked on
    alert(e.target);
})

The problem appears to be that although the function above triggers whenever I remove focus from the TR, the event is actually triggered by the child element (eg the TD, input box, button etc), not the parent element.

Is there any way to retrieve the original TR, without having to trace back through the parent of each object until I hit a TR element? Perhaps by passing the ID in directly when creating the function?

Upvotes: 2

Views: 1943

Answers (2)

charlietfl
charlietfl

Reputation: 171698

Use this or e.currentTarget instead of e.target

$(".row-identifying-class").focusout(function (e) {
    var rowID = this.id; 
    alert(rowID);
});

this within a jQuery event handler will be the element instance of the matching selector the event occured on

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337733

You're correct in that e.target will refer to the element that raised the new event which caused the focusout to fire on the tr.

Instead, use the currentTarget property as that will point to the event bound element instead, or more simply just this.id:

$(".row-identifying-class").focusout(function(e) {
  console.log(e.currentTarget.id);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr class="row-identifying-class" id="tr">
    <td>
      <input type="text" value="cause a focusout on me..." />
    </td>
  </tr>
</table>

Upvotes: 3

Related Questions