Get Off My Lawn
Get Off My Lawn

Reputation: 36299

jQuery each() not working

Am I doing something wrong here? I have an array of tags, and when I do a jQuery each() on the array it doesn't go into the each() I did have an alert in the each but nothing happens. I have checked my error log console and there are no errors. So, what am I doing wrong?

var tags = new Array();
tags["video-games"] = "Video Games";
tags["sports"] = "Sports";
tags["movies"] = "Movies";
tags["board-games"] = "Board Games";
tags["news"] = "News";
tags["television"] = "Television";
tags["computers"] = "Computers";
tags["opinions"] = "Opinions";
tags["reviews"] = "Reviews";

function updateTags(){
    console.log(tags);
    $("div.tags > div > span:first-child").nextAll().remove();
    $.each(tags, function(key, val){
        $("div.tags > div").append("<span><a class='tag' href='/tags/" + key + "'>" + val + "</a></span>");

    });
}

updateTags();

Upvotes: 0

Views: 2793

Answers (3)

Murali Murugesan
Murali Murugesan

Reputation: 22619

Your code is object and properties

var tags = {};
tags["video-games"] = "Video Games";

or

var tags = {
"video-games" : "Video Games";
};

Then

$.each(tags, function(key, val) {
    $("div.tags > div").append("<span><a class='tag' href='/tags/" + key + "'>" 
                                + val + "</a></span>");

});

Upvotes: 0

Akshay Khandelwal
Akshay Khandelwal

Reputation: 1570

So in this case

var tags = {};
tags["video-games"] = "Video Games";
tags["sports"] = "Sports";
tags["movies"] = "Movies";
tags["board-games"] = "Board Games";
tags["news"] = "News";
tags["television"] = "Television";
tags["computers"] = "Computers";
tags["opinions"] = "Opinions";
tags["reviews"] = "Reviews";

function updateTags(){
    //console.log(tags);
    $("div.tags > div > span:first-child").nextAll().remove();
    for(var key in tags){
        $("div.tags > div").append("<span><a class='tag' href='/tags/" + key + "'>" + tags[key] + "</a></span>");
    }
}

updateTags();

Should work.

Upvotes: 0

SLaks
SLaks

Reputation: 887305

Arrays are expected to have numeric indexes.
You've created an empty array which happens to have some properties.

You should create an ordinary object instead:

var tags = {
    "video-games": "Video Games",
    ...
};

Upvotes: 10

Related Questions