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>
CodePudding user response:
You don't actually need js to do this. For example I'm using jinja 2 template here like so to fill in my options list.
{% for item in db.subkeys %}<option>{{item}}</option>{% endfor %}
Where I'm passing in db.subkeys as list of strings.
CodePudding user response:
You can use .map prototype
datalist.innerHTML = suggestions.map((suggest, index) => {
return `<option value="${index}">${suggest.term}</option>`
})