复选框实现全选/全部选/反选
前端HTML代码:
<form action="delProfile" method="post">
<table border="1" cellpadding="0" cellspacing="0">
<thead>
<tr style="background-color: yellow;">
<td width="150"><input type="checkbox" id="all"/>全选/全不选</td>
<th width="100">编号</th>
<th width="100">姓名</th>
<th width="100">生日</th>
<th width="100">性别</th>
<th width="100">职业</th>
<th width="100">住所</th>
<th width="100">电话</th>
</tr>
</thead>
<tbody>
<c:forEach items="${profileList}" var="profile">
<tr>
<td><input type="checkbox" name="idChecked" value="${profile.id}"/></td>
<td>${profile.id}</td>
<td>${profile.name}</td>
<td>${profile.birthday}</td>
<td>${profile.gender}</td>
<td>${profile.career}</td>
<td>${profile.address}</td>
<td>${profile.mobile}</td>
</tr>
</c:forEach>
</tbody>
</table>
<input type="submit" value="删除所选"/>
</form>
JQuery代码:
<script type="text/javascript" src="jquery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function () {
if("${profileList}" == ""){
window.location="getAllProfile.action";
}
$("#all").click(function () {
$("[name=idChecked]").prop("checked",$(this).prop("checked")); //实现全选/全不选
});
$("[name=idChecked]").click(function () { //实现反选
var s = $("[name=idChecked]");
if(this.checked){
for(i=0;i<s.length;i++){
if(s[i].checked != true){
return;
}
}
$("#all").prop("checked",true);
}else{
$("#all").prop("checked",this.checked);
}
});
});
</script>
mybatis批量删除数据
action代码:
public class ProfileAction extends BaseAction{
private Profile profile;
public String del(){
String[] idChecked = getRequest().getParameterValues("idChecked"); //获取前端所选复选框的value
int [] idArray = new int[idChecked.length];
for (int i=0;i<idChecked.length;i++){ //把或取到的String数组转换为int数组
idArray[i] = Integer.parseInt(idChecked[i]);
}
ProfileService profileService = new ProfileService();
boolean result = profileService.delete(idArray);
if (result){
return SUCCESS;
}else {
String msg = "删除失败!";
getRequest().setAttribute("msg",msg);
return ERROR;
}
}
public Profile getProfile() {
return profile;
}
public void setProfile(Profile profile) {
this.profile = profile;
}
}
struts.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="my" extends="struts-default">
<default-action-ref name="index"/> //设置项目默认首页
<action name="index">
<result type="redirect">/index.jsp</result>
</action>
<action name="*Profile" class="cn.yunhe.action.ProfileAction" method="{1}">
<result type="">/index.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
mybatis的mapper执行语句:
<delete id="delete" parameterType="int">
DELETE FROM profile WHERE id IN
<foreach item="idArray" collection="array" open="(" separator="," close=")">
#{idArray}
</foreach>
</delete>