0

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.

pnuts
  • 58,317
  • 11
  • 87
  • 139
Abdus Sattar Bhuiyan
  • 3,016
  • 4
  • 38
  • 72
  • Nothing is wrong with the code - see answer – Stan Jun 26 '15 at 16:48
  • Possible duplicate of http://stackoverflow.com/questions/6827810/unable-to-set-data-attribute-using-jquery-data-api/6828180#6828180 and others – Stan Jun 26 '15 at 16:51

2 Answers2

4

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)
Stan
  • 985
  • 1
  • 7
  • 12
  • forgot to add the reference - https://api.jquery.com/data/ and http://stackoverflow.com/questions/6827810/unable-to-set-data-attribute-using-jquery-data-api/6828180#6828180 – Stan Jun 26 '15 at 16:48
0

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'));   
Abdus Sattar Bhuiyan
  • 3,016
  • 4
  • 38
  • 72