0

I want change repeatedly the attribute value of data-number="2" when .next is clicked. It works at the first attempt that means the browser gives data-number value as 3. But when I click next times, it doesn't change. It remains 3. Here my code:

<a class="prev" data-number="1">&#10094;</a>
    <a class="next" data-number="2">&#10095;</a>
</div>
<script>
    $(document).ready( function(){
        $('a.next').on( 'click', function(){
        var image_num = parseInt($(this).data('number')) + 1 ;
        var num_to_string = image_num.toString();
        var prev_value = $(this).attr("data-number", num_to_string );
            console.log(prev_value);

        } );
    } );
</script>

I want to have the value as 3, 4, 5 ....

Motahar Hossain
  • 567
  • 5
  • 10
  • 1
    You can find the reason why your code isn't working in @Barmar answer in the link I provided. It's good to know why your code is not working, rather than just copying a working solution. – Alisson Reinaldo Silva Dec 24 '17 at 18:36

2 Answers2

1

You didn't update the intended data-number-attribute, because you have to use data as well to update it. So I replaced this line:

$(this).attr("data-number", num_to_string )

with this line:

$(this).data("number", num_to_string);

$(document).ready(function () {
  $('a.next').on('click', function () {
    var image_num = parseInt($(this).data('number')) + 1;
    var num_to_string = image_num.toString();
    var prev_value = $(this).data('number', +num_to_string);
    console.log(num_to_string);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="prev" data-number="1">&#10094;</a>
    <a class="next" data-number="2">&#10095;</a>
</div>

The reason for this behaviour is that jquery handles data-attribute (data-number) differently than ordinary attributes like id because when dealing with data-attributes the DOM-element is actually not altered unlike with ordinary attributes, as this link states.

That's why both methods data and attr work different and can therefore not be used in combination as they are used in the question, because attr works with updated DOM-values but data does not.

Hope this helps.

Blauharley
  • 4,186
  • 6
  • 28
  • 47
-1

If you use data() jQuery will automatically cast numeric data attribute values to number

  $('a.next').on('click', function() {
    var $el = $(this);
    // increment the data object value of number property 
    $el.data().number ++;

    console.log('New number:', $el.data('number'))
  });
   
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="#" class="next" data-number="2">Next</a>
charlietfl
  • 170,828
  • 13
  • 121
  • 150