Aleski
Aleski

Reputation: 1442

Having trouble looping a JSON file to create manipulatable results to populate a drop down list

I am having problems remembering how to loop through an object to manipulate it into options in a select form object. I have gotten this far but the alert from inside the success function simply prints "object Object". I have done this before but I am just rusty and any help is appreciated.

function getDestinations()
{
$.ajax({
    dataType:'json',
    type:'GET',
    url:"json/destinations.json",
    success:function(data) {
        for (var dest in data.Destinations) {
            alert(dest.destinationName)
        }

    }
});
}

The alerts are coming up as "undefined" but they are looping the correct amount of times.

For more information, each returned result is to populate a dropdown list that will in turn be used, when selected, to populate a div with weather information for said selected location using its "destinationID".

Upvotes: 0

Views: 63

Answers (3)

TheCrzyMan
TheCrzyMan

Reputation: 1030

The other answers are correct, but here is why what you are doing isn't working. When you do a for each loop, the variable iterates through the indexes/keys in whatever you give it.

for (var dest in data.Destinations){
    // dest is an index/key within the data.Destinations variable
    // So you refer to it using
    alert(data.Destinations[dest].destinationName);
}

I hope that helps.

Upvotes: 1

Adil Shaikh
Adil Shaikh

Reputation: 44740

Try this -

success:function(data) {
        $.each(data.Destinations, function(i,v){
           alert(v.destinationName);
        });
}

To populate select

  $("#selectID").empty();
  $.each(data.Destinations, function(i,v){
          var dest = v.destinationName;
          $("#selectID").append("<option value="+dest+">"+dest+"</option>");
  });

Upvotes: 1

km6zla
km6zla

Reputation: 4877

$.each(object, function(index,value){
    //do stuff
});

Upvotes: 2

Related Questions