thymeleaf中th:checked
时间: 2023-10-13 15:48:56 浏览: 126
在Thymeleaf模板引擎中,`th:checked` 是用于处理HTML表单中的复选框的属性。
使用 `th:checked` 属性可以根据条件来决定是否选中复选框。它接受一个布尔值,当该值为 true 时,复选框将被选中;当该值为 false 时,复选框将不被选中。
以下是 `th:checked` 的用法示例:
```html
<input type="checkbox" th:checked="${isChecked}">
```
在上面的示例中,`${isChecked}` 是一个Thymeleaf变量,表示一个布尔值。如果 `isChecked` 为 true,则复选框将被选中;如果 `isChecked` 为 false,则复选框将不被选中。
您可以根据自己的业务逻辑来设置 `isChecked` 变量的值,以控制复选框的选中状态。
请注意,`th:checked` 属性只能用于处理复选框的选中状态,对于其他类型的表单元素(如单选按钮、下拉列表等),需要使用不同的Thymeleaf属性进行处理。
相关问题
Thymeleaf 中radio 选中怎么设置
在 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中获取checkbox的值
在Thymeleaf中获取checkbox的值可以通过以下代码实现:
```
<input type="checkbox" name="exampleCheckbox" th:value="true" th:checked="${exampleValue}"/>
```
其中,`th:value`属性设置checkbox选中时的值,可以是任意值,但通常是一个布尔值。`th:checked`属性则指定checkbox是否被选中,它的值可以是一个布尔表达式,比如`${exampleValue}`。
在Controller中,可以通过`@RequestParam`注解获取checkbox的值,如下所示:
```
@RequestMapping("/submit")
public String submitForm(@RequestParam("exampleCheckbox") boolean exampleValue) {
// 处理提交的表单数据
return "result";
}
```
这样,就可以获取到checkbox选中的值,然后进行相应的处理。