单选复选 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 内嵌变量