Thymeleaf 中radio 选中怎么设置
时间: 2023-12-14 11:39:48 浏览: 164
在 Thymeleaf 中,可以通过 th:checked 属性来设置 radio 的选中状态。当 th:checked 的值为 true 时,radio 选中;当 th:checked 的值为 false 时,radio 不选中。如下所示:
```html
<input type="radio" name="gender" value="male" th:checked="${user.gender == 'male'}"> Male
<input type="radio" name="gender" value="female" th:checked="${user.gender == 'female'}"> Female
```
在上面的示例中,根据 user 对象中的 gender 属性值来判断哪个 radio 应该被选中。如果 user.gender 的值为 "male",则第一个 radio 会被选中;如果 user.gender 的值为 "female",则第二个 radio 会被选中。
相关问题
thymeleaf radio
Thymeleaf is a server-side Java template engine that can be used for building web applications. Radio buttons are a common form element that allows users to select one option from a list of options. To create radio buttons using Thymeleaf, you can use the `th:each` and `th:field` attributes.
Here's an example:
```
<form>
<div th:each="fruit : ${fruits}">
<input type="radio" th:field="*{selectedFruit}" th:value="${fruit}" />
<label th:text="${fruit}"></label>
</div>
</form>
```
In this example, `fruits` is a list of fruit options that you want to display as radio buttons. The `th:each` attribute is used to iterate over the list and create a radio button for each option.
The `th:field` attribute is used to bind the selected option to a model attribute named `selectedFruit`. This means that when the form is submitted, the selected option will be assigned to the `selectedFruit` attribute in the model.
Finally, the `th:value` attribute is used to set the value of each radio button to the corresponding fruit option, and the `th:text` attribute is used to display the fruit option label next to each radio button.
thymeleaf 根据下拉框选中的值
可以使用Thymeleaf的条件表达式来根据下拉框的选中值来展示不同的内容。以下是一个简单的示例:
```html
<select name="fruit" th:modelAttribute="selectedFruit">
<option value="">--请选择--</option>
<option value="apple">苹果</option>
<option value="banana">香蕉</option>
<option value="orange">橘子</option>
</select>
<div th:if="${selectedFruit=='apple'}">
你选择了苹果。
</div>
<div th:if="${selectedFruit=='banana'}">
你选择了香蕉。
</div>
<div th:if="${selectedFruit=='orange'}">
你选择了橘子。
</div>
```
在上面的代码中,我们使用了Thymeleaf的`th:modelAttribute`属性来将下拉框的选中值绑定到后台的`selectedFruit`变量上。然后使用条件表达式`th:if`来判断`selectedFruit`的值,并展示相应的内容。
阅读全文