javascripthtmljsondatalist

Dynamically load JSON into a datalist (vanilla JS)


I've been spending the past couple of days researching on W3C and SO (this being the closest issue I found to mine), to dynamically load a "static" JSON into a dynamically created datalist.

More details on what I'm trying to achieve - I'm trying to create a form to add records to a database; default form allows to add one record, but there's a button to dynamically add another set of empty fields to submit multiple records at once. Once all form is filled in, this is sent to PHP for processing. I'm using bootstrap for the frontend (though I'll try to clean the code for readability).

  1. Load page for the first time, save the JSON into a "HTML variable". Note the page has already one datalist.
  2. Should the user click on the button to add another set of fields, these appear (including an additional datalist)
  3. Objective: this newly created datalist should be populated with the JSON saved in the HTML Variable in point no. 1

Two questions:

  1. Is this doable? As in, do HTML vars have a persistent scope even if I change the DOM?
  2. If so, what am I doing wrong in the code below?
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>?do=addnewstructure" enctype="multipart/form-data">
  <input list="datalistOptions" id="datalisttype1" name="deftype_ent[]" placeholder="Type to search..." onFocus="populate_datalist(types_json);">
    <datalist id="datalistOptions">
      <option value="first">First persistent option</option>
    </datalist>
</div>
<div>
  <label for="value_ent">Name</label>
  <input type="text" name="defvalue_ent[]" id="value_ent">
</div>
<div>
  <label for="relevance_ent">Relevance</label>
  <select id="relevance_ent" name="relevance_ent">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
  </select>
</div>

<script>
var types_json = document.createElement("list_of_types");

var dataList = document.getElementById("datalisttype1");


var types_json = [<?php
  echo json_encode($results_json); // This is coming from backend, it is valid JSON
?>];

// Loop over the JSON array.
function populate_datalist(which_dl)
{
    which_dl.forEach(function(item) {
    var option = document.createElement('option');
    
    option.value = item.type_id;
    option.text = item.name;

    dataList.appendChild(option);
});
}

</script>
<button type="submit">Add</button>
</form>

I know this may be a noob question as I just started with js, only did BE languages so far. Thanks for your help! :)


Solution

  • For anyone stumbling upon this code in the future - I got it work and there are a variety of reasons why it wasn't working previously.

    In brief:

    TLDR; do not rely on the code above, even as an inspiration :)