简体   繁体   English

如何在 html 中弹出输入标签的数据列表选项

[英]how to pop up datalist options for input tag in html

I'm currently trying to add to my datalist for my input text field in html.我目前正在尝试将 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.我这样做的方法是从后端检索文本并在 datalist 中动态生成选项,但是,在我在前端检索所有文本并为 datalist 生成选项之后,只有一个选项显示而不是全部。

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:这是我的 html:

        <label for="q">Input</label>
        <input type="text" name="q" id="q" list="suggestions" onchange="getSuggestedWords(event)" autocomplete="on">
        <datalist id="suggestions">
        </datalist>

You don't actually need js to do this.您实际上并不需要 js 来执行此操作。 For example I'm using jinja 2 template here like so to fill in my options list.例如,我在这里使用 jinja 2 模板来填写我的选项列表。

{% for item in db.subkeys %}<option>{{item}}</option>{% endfor %}

Where I'm passing in db.subkeys as list of strings.我将 db.subkeys 作为字符串列表传入的地方。

You can use.map prototype您可以使用.map原型

 datalist.innerHTML = suggestions.map((suggest, index) => { return `<option value="${index}">${suggest.term}</option>` })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM