I've tried a lot of different implementations of updating datalist options from a fetch request, but every one I've done results in unreliable behavior in usage.
I have this huge dynamically created cell in a table which when created autopoulates the identity fields with the row number:
cell2.innerHTML = '<td scope="row"> <input form="form' + rowNumber + '" type="text" name="productCode" id="form' + rowNumber + 'productCode" value="" '
+ 'class="form-control" list="datalist' + rowNumber + 'productCode" onInput="searchProductCode(' + rowNumber + ')" autocomplete="false" />'
+ '<datalist id="datalist' + rowNumber + 'productCode"></datalist>' + '</td>';
And calls this function on user input:
async function searchProductCode(rowNumber) {
var data = document.getElementById("form" + rowNumber + "productCode").value;
var dataList = document.getElementById("datalist" + rowNumber + "productCode");
dataList.innerHTML = ""
if (data.length < 3) {
return
}
var products = await searchAtServer("/products/search", data)
for await (product of products) {
let option = document.createElement("option");
option.setAttribute("data-id", product.id);
option.value = product.code;
dataList.appendChild(option);
}
The searchAtServer function is an async fetch:
async function searchAtServer(address, data) {
return fetch(address, {
method: 'post',
headers: { 'Content-Type': 'text/plain' },
body: data
})
.then(function (response) {
return response.json();
})
.catch(function (error) {
console.log(address + 'Request failed', error);
})
}
It posts reliably and captures user input reliably but the datalist field doesn't autopopulate reliably. Sometimes it has the correct options but other times it doesn't behave as I expect: not listing anything, listing numbers 1/2, listing numbers 1/2+the correct response, listing old responses.
My main goal is to autopopulate a dropdown list of options from the server for entry.