Reputation: 3074
I want to update the value of data attribute. I checked showing alert message but when I inspect element the value is not updated. Here is my code:
alert(pid); // show 1
alert($('#buybtn').data('id')); // show 'hello'
$('#buybtn').data('id',pid);
alert($('#buybtn').data('id')); // show 1
But after this code run I checked the data attribute value. It shows previous data as follows:
What is the wrong in my code? Thanks for your time.
Upvotes: 0
Views: 1048
Reputation: 3074
I found a tricks to solve this. As data attribute can't be updated I removed that and add with update value.
$('#buybtn').attr('data-id');
$('#buybtn').attr('data-id',pid);
alert($('#buybtn').data('id'));
Upvotes: 0
Reputation: 983
jQuery's data attribute does not update the visible HTML markup - it only updates an internal copy of the data. This performs better and works perfectly as long as you always use jQuery.data()
to access/change.
Otherwise, use jQuery.attr('data-id', pid)
not recommended:
$('#buybtn').attr('data-id', pid)
Upvotes: 4