Scroll JSON array and fill select dynamically

3

I am trying to fill <select> from the data stored in a JSON array. My code is as follows:

applications = {
  "apps": [
    { "app":"app_uno", "buzon":"buzon_uno" },
    { "app":"app_dos", "buzon":"buzón_dos" }
  ]
};

function fillSelector(options_list) {	
  var options = options_list; 
  var modelList = document.getElementById("select_form"); 
  for (var i in options.apps) { 
    var opt = options.apps[i].app; 
    modelList.options.add(opt);
  }
} 

fillSelector(applications);
<select id="select_form">
  <option value="">Seleccione una opción</option>
<select>

In this example I would have to store the values "one", "two", etc. in "opt". I do not know where the problem is since I've never used JSON, this time it's the first time I use it.

    
asked by Alex Alvarez 07.07.2018 в 14:22
source

1 answer

2

The problem you're not having when traversing JSON, which is correct. The problem is when you add the option to the select because with select.options.add you expect that what you're going to happen is an element of type option but you're passing an object that is not.

To solve that, you could create a option and pass it to add . Here I leave your code with the changes mentioned:

applications = {
  "apps": [
    { "app":"app_uno", "buzon":"buzon_uno" },
    { "app":"app_dos", "buzon":"buzón_dos" }
  ]
};

function fillSelector(options_list) {	
  var options = options_list; 
  var modelList = document.getElementById("select_form"); 
  for (var i in options.apps) { 
    // creamos un elemento de tipo option
    var opt = document.createElement("option");
    // le damos un valor
    opt.value = options.apps[i].app;
    // le ponemos un texto
    opt.textContent = options.apps[i].buzon;
    // lo agregamos al select
    modelList.options.add(opt);
  }
} 

fillSelector(applications);
<select id="select_form">
  <option value="">Seleccione una opción</option>
<select>
    
answered by 07.07.2018 / 14:38
source