Becky
Becky

Reputation: 5595

$.ajax json dropdown menu items

I'm trying to do a dropdown using json.

json:

[["a","Apple"],["b", "Berry"]]

JavaScript:

$.ajax({url:'fruit.json'}).done(function(data) { 
    var items = '<option value="" selected>Select</option>';
    $.each(data, function(i, val) {
        items += '<option value= "'+val[0]+'" > '+val[1]+' </option>';
    });
    $('#menu').html(items);
    console.log(items); //shows values correctly
});

html:

<script type="text/template" id="menuScriptWrapper">
    <select id="menu"></select>
</script>

Why aren't the items being populated in to the drop down menu?

Upvotes: 0

Views: 102

Answers (1)

Luca Putzu
Luca Putzu

Reputation: 1456

I realized a fiddle following your instructions, skipping ajax layer for simplicity sake (anyway if your console log shows your expected values ajax should be just fine)

Javascript:

var f = function(data) {
        console.log(data);
    var items = '<option value="" selected>Select</option>';
    $.each(data, function(i, val) {
        items += '<option value= "'+val[0]+'" > '+val[1]+' </option>';
    });
    $('#menu').html(items);
    console.log(items); //shows values correctly
};

f(([["a","Apple"],["b", "Berry"]]));

HTML

<select id="menu"/>

Fiddle

Everythink seem just fine. I'd say your problem lies somewere else on the page. I'd double check your menu selector... Check also you do not have more than one tags with the id="menu" attribute

Upvotes: 1

Related Questions