2

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?

user123892
  • 1,243
  • 3
  • 21
  • 38
  • 1
    I made you a snippet. Please add the data object – mplungjan May 03 '21 at 11:14
  • 1
    When you do, we can find a MUCH shorter script for you – mplungjan May 03 '21 at 11:14
  • 2
    I never seen option self closing option tags – mbesson May 03 '21 at 11:23
  • 2
    What is the problem? Can you post the generated html? One way to shorten this simple change the variable name parameter_enum_array to something like values. Here's an example of short clean code that you want to move towards. https://stackoverflow.com/questions/6601952/programmatically-create-select-list – react_or_angluar May 03 '21 at 11:31
  • 1
    @jqueryHtmlCSS that is valid jQuery. – T J May 03 '21 at 11:40
  • 1
    Does this answer your question? [Programmatically create select list](https://stackoverflow.com/questions/6601952/programmatically-create-select-list) – biberman May 03 '21 at 11:43

2 Answers2

2

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>
T J
  • 42,762
  • 13
  • 83
  • 138
  • thank you for your time T J. I flagged the other answer as the solution just because it is more "compact" :-) – user123892 May 03 '21 at 15:46
  • @user123892 that looks compact but bad for performance. It does multiple DOM updates for each form.My answer contains strings and objects expanded for readability. They can't be made into 1liner as well. – T J May 03 '21 at 15:51
2

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>
charlietfl
  • 170,828
  • 13
  • 121
  • 150