tags:

views:

165

answers:

4

Whats the best way to increment a value in a jQuery .data() object?

+2  A: 

I think you will have to read the value and write it back, so:

$(element).data('yourKey', $(element).data('yourKey') + 1);

After all, data() is a function call, and incrementing the result will not modify the value itself, which sits in an internal jQuery data structure.

Tom Bartel
+3  A: 
var data = parseInt ($.data("data-attr")) + 1;

$.data("data-attr",data);
rahul
+8  A: 

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
gnarf
Thanks! While my way works in this particular case, yours is the more JavaScripty way of doing it, and is the correct answer for the general case. Yours may even be shorter if you keep the reference: `var v = {value:1}; $elem.data('something', v); /*...*/ v.value++;`
Kobi
+6  A: 

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
Kobi
+1 Nice catch!!
Reigel