Getting no options into a dynamical filled select tag

Viewed 62

I'd need to programmatically fill a select dropdown element with the values of an array. I've read plenty of similar questions but could not find an answer solving my issue.

I have the following

const data = {
   parameters:[{"name":"myparam","type":"enum","values":["5","10","15"]}   
   ]
}

$.each(data.parameters, function(i, parameter) {
  // parameter = {"name":myparam","type":"enum","values":["5","10","15"]}
  let param_form_id = parameter.name + "_id";

  let parameter_enum_array = new Array();
  // push all values to parameter_enum_array[]
  $.each(parameter.values, function(j, enumvalue) {
    parameter_enum_array.push(enumvalue);
  });
  let select_id = parameter.name + "_sel_id";

  // create form with empty select element
  $('<form>', {
    "id": param_form_id,
    "html": '<div class="input_field s12 l6"> <select id="' + select_id + '">  </select> </div> <div class="col s12 l6"><button class="btn blue" type="submit"> submit</button> </div>'
  }).appendTo(`.params_container`);

  // add options to select element
  var option = '';
  for (var i = 0; i < parameter_enum_array.length; i++) {
    $('<option/>').val(parameter_enum_array[i]).html(parameter_enum_array[i]).appendTo(select_id);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="params_container">

</div>

The resulting html code

<form id=myparam_id>
   <div class="input_field s12 l6">
      <select id="myparam_sel_id">  </select>
   </div>
   <div class="col s12 l6">
     <button class="btn blue" type="submit"> submit</button> 
   </div>
</form>

The issue is that the is empty.

What am I doing wrong?

2 Answers

The problem with your code is missing # for the selector at .appendTo(select_id), which can be fixed with .appendTo('#' + select_id).
Also here "id": param_form_id param_form_id is not defined.


I recommend doing this as shown below, using template literals and Array.map() in order to minimise actual DOM manipulations:

const data = [{
  "name": "myparam",
  "type": "enum",
  "values": ["5", "10", "15"]
}, {
  "name": "myparam1",
  "type": "enum",
  "values": ["5", "10", "15"]
}];
const forms = [];
$.each(data, function(i, parameter) {
  const options = parameter.values.map(value => `<option>${value}</option>`).join('');
  const htmlTempate = `<div class="input_field s12 l6">
                          <select id="${parameter.name}_sel_id">${options}</select>
                        </div>
                        <div class="col s12 l6">
                          <button class="btn blue" type="submit"> submit</button>
                        </div>`
  forms.push($('<form>', {
    id: 'param_form_id_' + i,
    html: htmlTempate
  }));
});

$('.params_container').append(forms);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="params_container"></div>

If you store the newly created <form> element object in a variable you can manipulate it with jQuery before inserting into the dom

Here I create the options using:

const $opts = parameter.values.map(v => new Option(v,v));

Then append that to the select inside the variable. When all that is done append the form to the DOM

const data = {
   parameters:[{"name":"myparam","type":"enum","values":["5","10","15"]}   
   ]
}

$.each(data.parameters, function(i, parameter) { 
 
  let select_id = parameter.name + "_sel_id";

 // new form element assigned to variable
 const $form= $('<form>', {
    "id": 'param_form_id_' + i,
    "html": '<div class="input_field s12 l6"> <select id="' + select_id + '">  </select> </div> <div class="col s12 l6"><button class="btn blue" type="submit"> submit</button> </div>'
  });
  // map array of option elements
  const $opts = parameter.values.map(v => new Option(v,v));
  // insert options into select
  $form.find('#' + select_id).append($opts)
  // append whole form including the options
  $(`.params_container`).append($form);

 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="params_container">

</div>

Related