Reputation: 350
So I have a DataTable
and I want to update data attribute data-paiement
on the last a
of my td
. Here is an example :
<td class="dropdown open">
<a class="btn btn-default" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"><i class="fa fa-cog"></i></a>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="/fr/admin/evenements/inscriptions/modifier?URL=noel-des-enfants-2017&id=3440">Modifier</a><br>
<a class="dropdown-item" href="#" data-delete-inscription="3440" onclick="DeleteInscription(3440, 'DEMN')">Supprimer</a><br>
<a class="dropdown-item btnPaiement" href="#" data-update-paiement="3440" data-paiement="1" data-acronym="DEMN">Changer le statut de paiement</a><br>
</div>
So, when I click on it, I call a jQuery function and I send this data attribute
:
$(document).on('click', '.btnPaiement', function () {
console.log($(this).data('paiement'));
ChangeStatusPaiement($(this).data('update-paiement'), $(this).data('acronym'), $(this).data('paiement'));
});
In ChangeStatusPaiement
, I update the data-paiement
like this :
$('a[data-update-paiement="' + id + '"]').attr('data-paiement', paye == 1 ? '0' : '1');
All is ok, the HTML is updated, so data-paiement
now equals 0
But, when I re-click on it, in my console.log($(this).data('paiement'));
of my jQuery Call, data-paiement
value is still 1
Is it because the DataTable
does not update his value ?
Thanks !
Upvotes: 0
Views: 1217
Reputation: 3456
Accessing jQuery .data()
function creates an in-memory object containing the element's data attributes values. Using jQuery .attr()
function to alter attributes values will only update the attribute itself but changes will not be reflected onto the underlying data model handled by jQuery.
In ChangeStatusPaiement
you might need to replace:
$('a[data-update-paiement="' + id + '"]').attr('data-paiement', paye == 1 ? '0' : '1');
with:
$('a[data-update-paiement="' + id + '"]').data('paiement', paye == 1 ? '0' : '1');
A demo here:
let $tester = $('span');
$('div').append($('<p />', {text: 'Accessing data the first time: '+$tester.data('test')}));
$tester.attr('data-test', 2);
$('div').append($('<p />', {text: 'Accessing data twice (after update): '+$tester.data('test')}));
$('div').append($('<p />', {text: 'Nevertheless the attribute has been updated using attr function in the meantime: '+$tester.attr('data-test')}));
$('div').append($('<p />', {text: 'You have to modify via the data function. $("span").data("test", 2)' + ($("span").data('test', 2), '')}));
$('div').append($('<p />', {text: 'Now, accessing the value via "data function will give you the right value:' + ($tester.data('test'))}));
$('div').append($('<p />', {text: 'So use $element.data once "data" function has been called at least once for the element.'}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span data-test="1"></span>
<div></div>
Upvotes: 2