I am trying to implement an auto complete dropdown with dynamic data but it doesnt display any suggestions in the dropdown. I am using this example - Datalists: https://getbootstrap.com/docs/5.1/forms/form-control/ which works fine with predefined option tags.
<label for="exampleDataList" class="form-label">Datalist example</label>
<input class="form-control" list="datalistOptions" id="exampleDataList" placeholder="Type to search...">
<datalist id="datalistOptions">
... dynamic data here
</datalist>
I do receive data from the PHP script and they are correctly accessed but I think the problem might be due to the delay of the fetch. HTML might expect the data to already be there when loaded. That's why maybe it works with existing data.
here is the javacsript code inside the fetch function where I dynamically produce the tags:
var select = document.getElementById("datalistOptions");
select.innerHTML = "";
for (var key in data['result']) {
var val = data['result'][key];
if (data['result'].hasOwnProperty(key) && key != "error") {
var val = data['result'][key];
if (val != "") {
var option = document.createElement("option");
option.value = val.id;
select.appendChild(option);
}
}
}
Update: I changed the js code a bit. Now it uses appendChild instead of add function. The previous one was not adding any options to the datalist. appendChild does add options to the list but it does not display them.
This is a simpler version of what you trying to do. Try to take it, add your conditions, and make that data come in that form if you can.
var data = ["Haifa","Tel Aviv","Jerusalem"];
var select = document.getElementById("datalistOptions");
select.innerHTML = "";
for (var key in data) {
var option = document.createElement("option");
option.label = data[key];
option.value = data[key];
select.appendChild(option);
}
And make sure you adds onclick event that calls you script, maybe this is you problem, that you not calling the script - I would recomand somethig like that:
<input onclick="datalistCreate()" class="form-control" list="datalistOptions" id="exampleDataList" placeholder="Type to search...">
datalistCreate() is the function name in the script.