Abdus Sattar Bhuiyan
Abdus Sattar Bhuiyan

Reputation: 3074

Data attribute value can't be updated

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: enter image description here

What is the wrong in my code? Thanks for your time.

Upvotes: 0

Views: 1048

Answers (2)

Abdus Sattar Bhuiyan
Abdus Sattar Bhuiyan

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

Stan
Stan

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

Related Questions