Daniel Cotter
Daniel Cotter

Reputation: 1464

jQuery data() method resetting previously set data in a loop

OK, so I'm trying to store two pieces of data in a bunch of anonymous divs that are being appended to a parent div:

var $timepicker = $('<div class="timepicker"></div>');
var startTime = new Date(0, 0, 0, 0, 0, 0, 0);
var endTime = new Date(0, 0, 0, 23, 60 - settings.step, 0, 0);

for (var time = startTime; time <= endTime; time.setMinutes(time.getMinutes() + 30)) {
    $timepicker.append($('<div></div>').data('time', time));
}

However, after running the for loop, the value of data('time') is always equal to the last time's value, for each and every div (whereas it should be equal to the time that it was originally set to, obviously). I've scoured the interweb for clues, but no one else seems to be having this problem. What the heck's going on? Is it because I'm using anonymous divs? Your help is much appreciated.

Thanks,

Daniel

Upvotes: 0

Views: 252

Answers (2)

Daniel Cotter
Daniel Cotter

Reputation: 1464

For those curious, it turns out it wasn't working because JS was holding a reference to time in each div, rather than the value passed. This is because JS only passes simple types as values; objects are passed as references. The workaround was to instantiate a new Date object with every iteration:

var $timepicker = $('<div class="timepicker"></div>');
var startTime = new Date(0, 0, 0, 0, 0, 0, 0);
var endTime = new Date(0, 0, 0, 23, 60 - settings.step, 0, 0);

for (var time = startTime; time <= endTime; time.setMinutes(time.getMinutes() + 30)) {
    $timepicker.append($('<div></div>').data('time', new Date(0, 0, 0, time.getHours(), time.getMinutes(), 0, 0)
}

Upvotes: 1

psychotik
psychotik

Reputation: 39019

use appendTo. append doesn't return the jQuery object

$('<div></div>').appendTo($timepicker).data('time', time));

Upvotes: 0

Related Questions