jsp页面根据控制器传递的值来选中checkbox
比如控制器传递:
model.addAttribute("student", student);
student.hobby = "登山,羽毛球,打牌";
jsp页面判断然后选中:
方法一:
使用jquery:
<label>爱好:</label>
<input type="checkbox" name="hobby" value="游泳">游泳
<input type="checkbox" name="hobby" value="跑步">跑步
<input type="checkbox" name="hobby" value="登山">登山
<input type="checkbox" name="hobby" value="羽毛球">羽毛球
<input type="checkbox" name="hobby" value="打牌">打牌
<script>
$(document).ready(function(){
var hobby = '${student.hobby}';
var hobby_a = hobby.split(",");
console.log(hobby_a);
for(var i=0; i < hobby_a.length; i++){
$("input[name='hobby'][value='"+hobby_a[i]+"']").prop("checked",true);
}
})
</script>方法二:
使用JSTL的fn:contains()函数
注意:搜索和被搜索的字符串后都加 ",";
避免: 被搜索字符中含 "羽毛球", 结果 无论搜索 "羽毛" 或者 "羽毛球",结果都找到
<label>爱好:</label>
<c:set var="hobbys" value="${student.hobby},"/>
<input type="checkbox" name="hobby" value="游泳" <c:if test="${fn:contains(hobbys, '游泳,')}">checked</c:if>>游泳
<input type="checkbox" name="hobby" value="跑步" <c:if test="${fn:contains(hobbys, '跑步,')}">checked</c:if>>跑步
<input type="checkbox" name="hobby" value="登山" <c:if test="${fn:contains(hobbys, '登山,')}">checked</c:if>>登山
<input type="checkbox" name="hobby" value="羽毛球" <c:if test="${fn:contains(hobbys, '羽毛球,')}">checked</c:if>>羽毛球
<input type="checkbox" name="hobby" value="打牌" <c:if test="${fn:contains(hobbys, '打牌,')}">checked</c:if>>打牌