jQuery操作动态生成的Checkbox,完成全选和反选,以删除某一行或几行

本人也是菜鸟,将工作中的一些心得体会总结一下,记录自己的成长历程。

情境描述:

       最近因项目需要,需完成如下功能:点击第一个Checkbox全选/反选,而后点击右侧任意一个删除图标,都可以删除所选择的行。

      

解决方案:

JSP页面关键代码:

<pre class="html" name="code"><table id="contentTable" class="table table-striped table-bordered table-condensed">
		<thead><tr><th><input type="checkbox" name="select" id="selectAll"/></th><th>名称</th><th>地点</th><th>主持人</th><th>类型</th><th>参会人员</th><th>创建者</th><th>备注</th><th>时间</th><th>附件</th><th>督办列表</th><shiro:hasPermission name="spv:meeting:edit"><th>操作</th></shiro:hasPermission></tr></thead>
		<tbody>
		<c:forEach items="${page.list}" var="meeting" varStatus="status">
			<tr>
				<td> 
					<input type="checkbox" name="select" value="${meeting.id}"/>
				</td>
				<td><a href="${ctx}/spv/meeting/form?id=${meeting.id}">${meeting.meetingname}</a></td>
				<td>${meeting.site}</td>
				<td>${meeting.host}</td>
				<td>${meeting.meetingtype}</td>
				<td>${meeting.participates}</td>
				<td>${meeting.createBy.name}</td>				
				<td>${meeting.remarks}</td>
				<td><fmt:formatDate value="${meeting.meetingtime}" type="date" /></td>
				<td><input type="hidden" id="fileTest${status.index }"
						name="fileTest" value="${meeting.attachment}" /> <tags:ckfinderreadOnly
							input="fileTest${status.index}" type="files"
							uploadPath="/meetings" selectMultiple="true" />
				</td>
				 <td>
                    <ol>
                        <c:forEach items="${meeting.taskList}" var="tasks">
                        	 <c:if test="${tasks.delFlag == 0 }">
                            <li><a href="${ctx}/spv/task/form?id=${tasks.id}" title=" ${tasks.orderno }" 
                           οnclick="return view(this.href);">${fns:abbr(tasks.orderno,40)}</a></li>
                           </c:if>
                        </c:forEach>
                    </ol>
                    </td>
				<shiro:hasPermission name="spv:meeting:edit"><td>
					<a href="${ctx}/spv/task/formFromMeeting/${meeting.id}" title="增加督办"><i class="icon-plus bigger-130"></i></a>
    				<a href="${ctx}/spv/meeting/form?id=${meeting.id}" title="编辑会议" ><i class="icon-pencil bigger-130"></i></a>
					<a href="${ctx}/spv/meeting/delete?id=${meeting.id}" title="删除会议" id="delSelect" οnclick="return confirmx('确认要删除该会议吗?', this.href)"> <i class="icon-trash bigger-130"></i></a>
				</td></shiro:hasPermission>
			</tr>
		</c:forEach>
		</tbody>
	</table>
	<a href="javascript:delChoose();" οnclick="return confirmx('确认要删除吗?', this.href)" ><div class="btn btn-mini btn-info" id="hideDiv">
															<i class="icon-trash bigger-120"></i>
														</div></a>

Javascript代码:

<pre class="javascript" name="code">	<script type="text/javascript">
		
		/*为id为selectAll的复选框绑定click事件,使其具有全选、取消全选功能 */
		$(document).ready(function() {
			$("#hideDiv").hide();
			//为所id为selectAll的复选框绑定click事件,注:$("input:checkbox:first")与$("#selectAll")皆指向同一元素。
			$("#selectAll").bind("click",function(){
				if($("input:checkbox:first").attr("checked")){
					$("input[name='select']").attr("checked",true);
					hideOrShow();
				}else{
					$("input[name='select']").attr("checked",false);
					hideOrShow();
				}
			}); 
			//为所有的复选框绑定click事件,以响应hideOrShow()事件
			$("input:checkbox").bind("click",function(){
				hideOrShow();
			}); 
			
		}); 
		
		/* 判断是否显示删除按键 */
		function hideOrShow(){
			var items=$("input:checkbox:checked");
			var allItems=$("input:checkbox");
			if(items.length>0){
				$("#hideDiv").show();
			}else{
				$("#hideDiv").hide();
			}
			
			if(items.length<allItems.length){
				$("#selectAll").attr("checked",false);
			}
		}
		
		/* 为删除键赋予更强大功能,使其具有删除 选中复选框所指定的会议的功能 */
		function delChoose(){
			var items=$("input:checkbox:not(:first):checked");
			
			//普通请求提交方案
			var str="";
			for(var i=0;i<items.length;i++){
				str+=items.get(i).value+",";
			}
			window.location.href = "${ctx}/spv/meeting/deleteAll?str=" + str;
			
			//使用ajax请求方案:拼接JSON字符串
			/* var jsonStr="[";
			for(i;i<items.length;i++){
				  jsonStr+="{";
				  jsonStr+="id:";
				  jsonStr+=items.get(i).value;
				  jsonStr+="}";
				  
				  if(i!=items.length-1){
					  jsonStr+=",";
				  }
			 }
			 jsonStr+="]";
			//编码拼接后jsonStr,以便于后台能正确读取并解析
			 var jsonst = encodeURI(jsonStr);
			   $.post("${ctx}/spv/meeting/deleteAll",{ids: jsonst},function(data){
				   if(data=="Success"){
					   window.location.reload();
					   alert("删除成功!");
				   }
				   else{
					   alert("删除失败!");
				   }
				  
			   }, "text");  */		 
		  }
		
		function page(n,s){
			$("#pageNo").val(n);
			$("#pageSize").val(s);
			$("#searchForm").submit();
        	return false;
        }
	</script>

 

后台控制器代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.caini.supervision.common.config.Global;
import cn.caini.supervision.common.mapper.JsonMapper;
import cn.caini.supervision.common.persistence.Page;
import cn.caini.supervision.common.utils.StringUtils;
import cn.caini.supervision.common.web.BaseController;
import cn.caini.supervision.modules.spv.entity.Meeting;
import cn.caini.supervision.modules.spv.service.MeetingService;
import cn.caini.supervision.modules.sys.entity.User;
import cn.caini.supervision.modules.sys.utils.UserUtils;

/**
 * 会议Controller
 * @author 
 * @version 2014-06-04
 */
@Controller
@RequestMapping(value = "${adminPath}/spv/meeting")
public class MeetingController extends BaseController {

	@Autowired
	private MeetingService meetingService;
	
	@ModelAttribute
	public Meeting get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return meetingService.get(id);
		}else{
			return new Meeting();
		}
	}
	
	@RequiresPermissions("spv:meeting:view")
	@RequestMapping(value = {"list", ""})
	public String list(Meeting meeting, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		if (!user.isAdmin()){
			meeting.setCreateBy(user);
		}
        Page<Meeting> page = meetingService.find(new Page<Meeting>(request, response), meeting); 
        model.addAttribute("page", page);
		return "modules/spv/meetingList";
	}

	@RequiresPermissions("spv:meeting:view")
	@RequestMapping(value = "form")
	public String form(Meeting meeting, Model model) {
		model.addAttribute("meeting", meeting);
		return "modules/spv/meetingForm";
	}

	@RequiresPermissions("spv:meeting:edit")
	@RequestMapping(value = "save")
	public String save(Meeting meeting, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, meeting)){
			return form(meeting, model);
		}
		meetingService.save(meeting);
		addMessage(redirectAttributes, "保存会议'" + meeting.getMeetingname() + "'成功");
		return "redirect:"+Global.getAdminPath()+"/spv/meeting/?repage";
	}
	
	@RequiresPermissions("spv:meeting:edit")
	@RequestMapping(value = "delete")
	public String delete(String id, RedirectAttributes redirectAttributes) {
		meetingService.delete(id);
		addMessage(redirectAttributes, "删除会议成功");
		return "redirect:"+Global.getAdminPath()+"/spv/meeting/?repage";
	}
	
	/**
     * 删除复选框选中的会议
     */
	//对应于前台的普通提交方案
	@RequiresPermissions("spv:meeting:edit")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String str, RedirectAttributes redirectAttributes) {
		String[] strs=StringUtils.split(str, ",");
		for(String id:strs){
			meetingService.delete(id);
		}
		System.out.println(str);
		addMessage(redirectAttributes, "删除会议成功");
		return "redirect:"+Global.getAdminPath()+"/spv/meeting/?repage";
	}
		
    //对应于前台的ajax提交方案
	/*@RequiresPermissions("spv:meeting:edit")
	@RequestMapping(value = "deleteAll")
	public void deleteAll(String ids,HttpServletRequest request,HttpServletResponse response) throws IOException {
		String str = URLDecoder.decode(ids,"UTF-8");  
		JSONArray ja=JSONArray.fromObject(str);
		Iterator<JSONObject> it=ja.iterator();
		while(it.hasNext()){
			meetingService.delete((String) it.next().get("id"));
		}
		response.getWriter().write("Success");
	}*/
	
	 /**
     * 会议选择列表
     */
    @RequiresPermissions("spv:meeting:view")
    @RequestMapping(value = "selectList")
    public String selectList(Meeting meeting, HttpServletRequest request, HttpServletResponse response, Model model) {
        list(meeting, request, response, model);
        return "modules/spv/meetingSelectList";
    }

    /**
     * 通过编号获取会议名称
     */
    @RequiresPermissions("spv:meeting:view")
    @ResponseBody
    @RequestMapping(value = "findByIds")
    public String findByIds(String ids) {
        List<Object[]> list = meetingService.findByIds(ids);
        return JsonMapper.nonDefaultMapper().toJson(list);
    }

}


     这样,就很容易地实现了所需要完成的功能。在后台解析JSON字符串时,使用JSONArray之前应该导入JSON相关的Jar包。

     后来,需求有了点变化,要求点击复选框进行全选或部分选择时,在列表下面出来一个删除键(以<a>标签表示,点击任意复选框时出现,若复选框未被选取,则隐藏),点击它可以删除选中的行,而不是通过右侧的删除图标进行删除。某一行的删除图标用来直接删除某一行。

     所以,我们还要修改一下代码,在脚本中加入hideOrShow(),以判断是否显示列表下的删除键,同时设置其href属性值,href="javascript:delChoose();"。然后再将删除标志的href设置为:href="${ctx}/spv/meeting/delete?id=${meeting.id}"。这样便完成了变化后的需求。

     代码中包含两种前台js脚本发送请求至后台的方法,一种就是普通window.location.href = "${ctx}/spv/meeting/deleteAll?str=" + str方式,另外一种利用了$.post方法。同时后台也有相对应的接收请求的代码。



     



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值