Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 793
user3000731 Avatar asked Feb 13 '26 04:02

user3000731


1 Answers

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));
   }
});  
like image 86
MDiesel Avatar answered Feb 14 '26 17:02

MDiesel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!