首页 > 解决方案 > 如何为 Thymeleaf 输入字段添加默认值?

问题描述

这是我的百里香表单输入字段。我想为此设置一个默认值。假设我想将“个人”设置为默认值。怎么做?

 <div class="col-sm-9">
                            <label th:if="${#fields.hasErrors('priceSearchDTO.partyType')}" th:errors="*{priceSearchDTO.partyType}"
                                   class="validation-message"></label>
                            <input type="text" th:field="*{priceSearchDTO.partyType}" placeholder="partyType"
                                   class="form-control"/>
                        </div>

另外我试过这个,但它不能像普通的 html 字段那样工作。

<div class="col-sm-9">
                        <label th:if="${#fields.hasErrors('priceSearchDTO.partyType')}" th:errors="*{priceSearchDTO.partyType}"
                               class="validation-message"></label>
                        <input type="text" th:field="*{priceSearchDTO.partyType}" placeholder="partyType" value="individual"
                               class="form-control"/>
                    </div>

标签: thymeleaf

解决方案


有一个 th:placeholder 属性。您可以使用此属性动态设置占位符属性的值,例如:

<input ...  th:placeholder="${#object.individualPlaceholder}" ...>

或者

<input ...  th:placeholder="|Static and ${#object.dynamic}|" ...>

如果您的占位符是静态值,您仍然可以使用占位符属性:

<input ...  placeholder="Insert something" ...>

也可以为 th:placeholder 使用静态值。


推荐阅读