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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With