I’m currently trying to add to my datalist for my input text field in html. The way I do it is to retrieve text from backend and dynamically generate options in datalist, however, after I retrieve all texts at my frontend and generate option to datalist, there is only one option display instead all.
Here is the way I add option to my datalist:
async function getSuggestedWords(event) {
let datalist = document.getElementById("suggestions");
let text = document.getElementById("q").value;
let http = new XMLHttpRequest();
http.responseType = "json";
// let str = "";
http.onload = async function() {
if (this.readyState == 4) {
let {suggestions} = http.response;
for (let suggest of suggestions) {
console.log(suggest.term);
let s = document.createElement('option');
s.setAttribute("value", suggest.term);
datalist.appendChild(s);
}
}
}
const url = `http://localhost:8080/api/suggest?q=${text}`;
await http.open("GET", url);
await http.send();
}
here is my html:
<label for="q">Input</label>
<input type="text" name="q" id="q" list="suggestions" onchange="getSuggestedWords(event)" autocomplete="on">
<datalist id="suggestions">
</datalist>