首页 > 解决方案 > Thymeleaf 上的自动完成数据列表

问题描述

我正在使用 Thymeleaf 模板构建一个视图,其中包含一个表单,该表单提供了一种将我的输入值与模型中传递的属性绑定的方法。后端是使用 Spring 4 开发的。

以下代码段包含一个自动完成数据列表,其中包含名称列表对象的数据,该数据列表作为属性添加到模型中。所述名称列表是具有字段int id和的类的 ArrayList String name

<form th:action="@{/}" method="POST" th:object="${example}">
    <div class="form-group">
        <input list="names" class="form-control" id="nameinput" th:field="${example.num.id}">  </input>
        <datalist id="names">
            <option th:each="row : ${namelist}" th:value="${row.id}" th:label="${row.name}">
        </datalist>
        <button>submit</button>
    </div>
</form>

所选选项的值已经绑定到 example.num.id,这是预期和期望的行为。但是,当在 Web 浏览器上加载视图时(在最新的 Firefox 和 Chrome 上测试),它是这样表示的:

不受欢迎的 id 正在显示

如您所见,id 正在显示。但是,我正在尝试模仿 ; 的行为<select>。该值不应显示,仅显示文本或标签。

有没有更好的方法来实现这一目标?我没有正确使用数据列表吗?

标签: springdata-bindingautocompletethymeleafhtml-datalist

解决方案


推荐阅读