0

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?

5
  • $.ajax({url:'fruit.json'}) ==> $.ajax({url:'fruit.json', dataType: 'json'}) OR done(function(data) { data = JSON.parse(data);. Commented Mar 2, 2016 at 9:09
  • @Tushar Thanks. I tried , dataType: 'json'}) Did not work. I'm trying your other suggestion. Commented Mar 2, 2016 at 9:11
  • Just a silly question... do you have a <select id="menu"/> in your page? Commented Mar 2, 2016 at 9:12
  • @LucaPutzu Yes. Sorry, I've added it now. Commented Mar 2, 2016 at 9:12
  • @Tushar Thank you. Both your suggestions did not work. See Fiddle jsfiddle.net/9es752nL/1 Commented Mar 2, 2016 at 9:37

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks. This is my actual html jsfiddle.net/9es752nL/1 How can I get the dropdown populated? jsfiddle.net/9es752nL/1
@Becky: is there a reason for you to wrap your select in a <script type="text/html"></script> tag?
Thanks again Luca. Yes, it should be inside the <script type="text/template">. Currently the select menu is hard coded inside it and all works well. But now I have been asked to populate the select menu using JSON. Thanks again.
@Becky: are you using mustache.js or another client side template engine?
Nope, I'm not using them.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.