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).
Two questions:
<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! :)
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:
appendChild
wasn't attaching options to the datalist but to the inputTLDR; do not rely on the code above, even as an inspiration :)