Jeroen Bellemans
Jeroen Bellemans

Reputation: 2035

jQuery each() only selects last value

I have 2 list.

the first list holds all data. The other one are placeholders. And I have a button to take the default values. Which clones the first list into the placeholders.

Now I'm using this code to alert all the found data-id's. Which works fine.

But when I'm trying to paste those data-attributes onto the placeholders it always pastes the last value in each placeholder.

$(".default").click(function() {

    $("li.to-drag").each(function(index) {

        $("li.placeholder").addClass("dropped");

        var clone = $(this).clone();
        var day = $(this).attr("data-id");

            $("li.placeholder").each(function(){
                $("li.placeholder").attr("data-id", index);
            });

        clone.hide().appendTo("." + index).fadeIn(1500);

    });

    var dropped = $(".dropped").length;
    var original = $(".placeholder").length;

    if (dropped === original) {

        $("li.placeholder").removeClass(blank_placeholder);
        $("#dropzone").append('<li class="placeholder blank" data-id="" data-order=""></li>');

        init();
    }

});

How can I solve this?

SOLUTION:

I had to do a second each() loop outside the other one which iterated the .to-drag class.

$("li.placeholder").each(function(){
    var day = $(this).children().attr("data-id");
    $(this).attr("data-id", day);
});

Here is a jsfiddle

Upvotes: 0

Views: 529

Answers (1)

TheBalco
TheBalco

Reputation: 395

In your .each() loop, you have to use $(this), otherwise you will change everything everytime the loop repeats.

So just change the following part of your code:

$("li.placeholder").each(function(){
    $(this).attr("data-id", index);
});

Upvotes: 6

Related Questions