Whats the best way to increment a value in a jQuery .data()
object?
This looks a bit odd, but according to the docs .data()
returns all data fields as an object, so you can change its value directly:
$('#id').data('counter', 0);
Both options work:
$('#id').data().counter++; $('#id').data()['counter'] += 5;
Retrieving the data return the expected value:
alert($('#id').data('counter')); // 6
Or, if you control what you are storing, store an object reference so you can modify the values on the object directly using ++
:
var $elem = $('<div>'); $elem.data('something', {value:1}); $elem.data('something').value++; console.log($elem.data('something').value); // 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With