springboot - thymeleaf - 选中框默认选中

单选复选 checked

th:checked

单选框
例子:选中男女
后台Model对象传递属性值:

model.addAttribute("sex", "0");

html页面:

<input th:checked="${sex} eq '0'" type="radio" name="sex" value="男"/>男<br/>
<input th:checked="${sex} eq '1'" type="radio" name="sex" value="女"/>女

效果:
在这里插入图片描述

复选框
例子:选中多个爱好
后台Model对象传递属性值:

model.addAttribute("hobby", "篮球, 足球,羽毛球");

html页面:这里使用到thymeleaf的内嵌变量strings

<input th:checked="${#strings.contains(hobby,'足球')}" type="checkbox" value="足球"/>足球<br/>
<input th:checked="${#strings.contains(hobby,'王者峡谷')}" type="checkbox" value="王者峡谷"/>王者峡谷<br/>
<input th:checked="${#strings.contains(hobby,'篮球')}" type="checkbox" value="篮球"/>篮球<br/>
<input th:checked="${#strings.contains(hobby,'羽毛球')}" type="checkbox" value="羽毛球"/>羽毛球<br/>

效果
在这里插入图片描述

下拉选择框 select

th:selected

1.后台Model对象传递属性值

model.addAttribute("name", "ls");

2.html

<select>
    <option th:selected="${name == 'zs'}"> 张三 </option>
    <option th:selected="${name == 'ls'}"> 李四 </option>
    <option th:selected="${name == 'ww'}"> 王五 </option>
</select>

3.效果
在这里插入图片描述

补:可在select标签中使用 th:field="${值}" 来下拉选中
例:	<select  th:field="${2}">
		<option value="1">111</option>
		<option value="2">222</option>
		<option value="3">333</option>
	</select>
	选项222会被选中

第二种情况。后台多条数据添加到下拉框选项中

List<String> partList = new ArrayList<String>();
partList.add("财务部");
partList.add("行政部");
partList.add("人事部");
partList.add("后勤部");
model.addAttribute("partList", partList);

html

<select>
    <option>请选择部门</option>
    <option th:each="p:${partList}" th:value="${p}" th:text="${p}"></option>
</select>

效果
在这里插入图片描述
标签内再加个 th:selected="${p==‘人事部’}" 设置选中

在这里插入图片描述


上一章 thymeleaf 三元(三目)运算

下一章 thymeleaf 内嵌变量

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值