Reputation: 5911
I need to update a data-attr every time user clicks on a btn. But its not working how it should. Here is a demo code:
$('div.wrapper').on('click', 'div.btn', function(){
var thisGuy = $(this),
offset = thisGuy.data('showreplies');
thisGuy.attr('data-showreplies', parseInt(offset) + 10);
$('div.dataAttr').show().text(thisGuy.data('showreplies'));
});
Here is the DOM:
<div class="wrapper">
<div class='btn' data-showreplies='10'>Click Me</div>
</div>
<div class="dataAttr"></div>
What i wanted to do is that when a user will click on the btn then the value of the data-showreplies attr will be incremented to 10 and then it will display the updated value inside the div.dataAttr, for every click it will do the incrementation.
Upvotes: 0
Views: 65
Reputation: 4711
The data function can also be used as a setter:
$('div.wrapper').on('click', 'div.btn', function(){
var thisGuy = $(this),
offset = thisGuy.data('showreplies');
thisGuy.data('showreplies', parseInt(offset) + 10);
$('div.dataAttr').show().text(thisGuy.data('showreplies'));
});
Note that the attribute in the DOM stays 10, because jQuery has an internal cache for data values.
Upvotes: 1
Reputation: 2820
try to change
thisGuy.attr('data-showreplies', parseInt(offset) + 10);
to
thisGuy.data('showreplies', parseInt(offset) + 10);
Upvotes: 4