user3000731
user3000731

Reputation: 93

Creating Select Box from options stored in a variable

I want to create a select box from options stored in a variable (the values will change based on the user).

For now, I'm just trying to get it to work with this variable in my javascript file:

  var resp = {"streams": [ {"sweet":"cookies"}, {"savory":"pizza"}]}

In the html file, I have a select id "selectedStream"

How do I invoke, both the select id from html and the variable from javascript to create the select box?

I've seen examples such as the one below, but I don't understand how to link the id and the variable to the box.

  $("option:selected", myVar).text()

I hope this was coherent! Thanks

Upvotes: 3

Views: 83

Answers (2)

Carl Edwards
Carl Edwards

Reputation: 14474

Is that array necessary? If you're just trying to display the keys within that object I'd create a for loop:

var resp = { "streams": {"sweet": "cookies", "savory": "pizza"} }

for (property in resp.streams) {
    $('#selectStream').append($('<option/>', {text: property, value: property}));
}

JSFiddle: http://jsfiddle.net/pWFNb/

Upvotes: 0

MDiesel
MDiesel

Reputation: 2667

I think what you are trying to do is append option html nodes to an existing select element on your screen with an id of 'selectedStream'. You want to use the data from the 'resp' variable to populate the text and value of the option nodes that you are appending. If this is correct, I have implemented that functionality with this jsfiddle. The javascript is also below:

$(function(){
   var resp = {"streams": [ {"sweet":"cookies", "savory":"pizza"}]};
   var streamData = resp.streams[0];
   var optionTemplate = "<option value=\"{0}\">{1}</option>";
   for(var key in streamData){
       var value =  streamData[key];
       var currentOptionTemplate = optionTemplate;
       currentOptionTemplate = currentOptionTemplate.replace("{0}", key);
       currentOptionTemplate = currentOptionTemplate.replace("{1}", value);
       $("#selectedStream").append($(currentOptionTemplate));
   }
});  

Upvotes: 3

Related Questions