js里几个写法,第一次写,记录一下
1.jsp页面的样式
<div class="row cl">
<label class="form-label col-xs-4 col-sm-2"style="text-align: right;">车辆属性:</label>
<div class="formControls col-xs-8 col-sm-9">
<dl class="permission-list" style="width: 310px;">
<dt>
<label>
<input type="checkbox" value="" name="user-Character-0" id="checkAll"
//jsp页面比较两个list的长度 : ${fn:length(list1)==fn:length(list2) },使用fn要在页面引入<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:if test="${fn:length(autobasic.autoattributeList)==fn:length(autobasic.automappingattrList) }"> checked="checked" </c:if>
>全选:</label>
</dt>
<dd>
<c:forEach items="${autobasic.autoattributeList }" var="autoattribute" varStatus="status">
<label class="attrcheboxclass">
//在input中再加入一个foreach循环遍历判断每个checkbox是否被选中,如果被选中,则在input中添加checked属性
<input type="checkbox" class="checkOne" name="checkbox_name" value="${autoattribute.autoattributeId }"
<c:forEach items="${autobasic.automappingattrList}" var="automappingattr">
<c:if test="${automappingattr.autoattributeId == autoattribute.autoattributeId}">checked="checked"</c:if>
</c:forEach>
>
${autoattribute.name }</label>
</c:forEach>
</dd>
</dl>
</div>
</div>
效果如图:
2.获取复选框中的值
var idStr = "";
$("input[name='checkbox_name']").each(function(){
if($(this).is(":checked")){
//这里用逗号将字符串分隔开,传到后台后再分开取值
idStr+=$(this).val()+",";
}
});
entity.temporary = idStr;
下面是后台代码:
String[] strs = autobasic.getTemporary().split(",");
for (int i = 0; i < strs.length; i++) {
temp.setAutoattributeId(Integer.parseInt(strs[i]));
保存入对应的数据库
this.automappingattrService.insert(temp, "Automappingattr");
}
3.js里面实现全选和全不选:
checkAll为全选框的id
$("#checkAll").click(function() {
当全选框的属性改变为checked属性时,所有name为checkbox_name的checkbox循环遍历一次,并且都被选中,此处使用prop。
if($(this).is(':checked')) {
$("input[name='checkbox_name']").each(function(){
$(this).prop("checked",true);
});
当全选框由checked被点击为false时,所有name为checkbox_name的checkbox循环遍历一次,并且都不被选中
}else{
$("input[name='checkbox_name']").each(function(){
$(this).prop("checked",false);
});
}
});
当checkBox框被点击时,遍历所有的name为checkbox_name的单选框,如果所有的单选框都被选中时,那么全选框也会被勾选
$("input[name='checkbox_name']").click(function(){
var flag = true;
$("input[name='checkbox_name']").each(function(){
if(!$(this).is(":checked")){
flag = false;
}
});
if(flag==true){
$("#checkAll").prop("checked",true);
}else{
$("#checkAll").prop("checked",false);
}
});