Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .data() : possible to increment (++ or --)?

Tags:

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

like image 352
Haroldo Avatar asked Apr 22 '10 07:04

Haroldo


2 Answers

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 
like image 118
Kobi Avatar answered Jan 27 '23 14:01

Kobi


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 
like image 24
gnarf Avatar answered Jan 27 '23 13:01

gnarf