0

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.

JsFiddle Link: https://jsfiddle.net/hasantg/knwpdw42/6/

2 Answers 2

4

try to change

 thisGuy.attr('data-showreplies', parseInt(offset) + 10);

to

 thisGuy.data('showreplies', parseInt(offset) + 10);
Sign up to request clarification or add additional context in comments.

1 Comment

hmmm.its working fine once i change those lines on your fiddle
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.