Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting parent ID on child click

I'm tryng to get parent id on click with jquery.

My django template is as follows :

<table id="archive-table" class="table table-hover table-vcenter">
    <thead>
       <tr>
          <th>Make and model</th>
          <th>First registration</th>
       </tr>
    </thead>
    <tbody>
       {% for calculation in calculations %}
          <tr data-archive-row class="archive-row" data-calculation-id={{ calculation.id }}>
               <td>{{ calculation.first_registration }}</td>
               <td>{{ calculation.body }}</td>
           </tr>
       {% endfor %}
     </tbody>
</table>

And my js is as follows :

<script>
    $(document).ready(function () {
        $('#archive-table').on('click', '[data-archive-row]', function (e) {
            var calculation_id = e.target.dataset['calculationId'];
            alert(calculation_id)
        })
    });
</script>

How can I get the dataset['calculationId'] of the parent no matter if I clicked on child.

With my code I'm getting undefined in alert. But If I for example add data-calculation-id={{ calculation.id }} to one td and if I then click on it then I'm getting the right id.

Is there any way to get the id from parent no matter if it's clicked on child or on parent?

like image 733
Boky Avatar asked Dec 24 '22 20:12

Boky


1 Answers

Use e.currentTarget, not target:

$(document).ready(function() {
  $('#archive-table').on('click', '[data-archive-row]', function(e) {
    var calculation_id = e.currentTarget.dataset.calculationId;
    alert(calculation_id)
  })
});

Since you are delegating event, e.currentTarget will be TR element, and target will be whatever you clicked within this TR, maybe TD or something in it.

Another simple solution is to simply use this as it will point to TR always in event handler:

var calculation_id = this.dataset.calculationId;
like image 67
dfsq Avatar answered Dec 26 '22 09:12

dfsq