jQuery+SpringMVC中的復選框選擇與傳值


一、checkbox選擇

在jQuery中,選中checkbox通用的兩種方式:

$("#cb1").attr("checked","checked");
$("#cb1").attr("checked",true);

對應的jQuery函數,主要完成三個功能:

1、第一個復選框選中或取消選中,則下面的復選框為全選或取消全選;

2、當下面的復選框全部選中時,則將第一個復選框設置為選中,當下面的復選框中有一個沒有被選中時,則第一個復選框取消選中;

3、將下面的復選框的id值傳遞給Controller層,組成id數組,然后調用相應的方法(一般都是刪除)。

<script type="text/javascript">    function chgAll(t){//第一個復選框選中或取消選中,則下面的復選框為全選或取消全選;
        $("input[name='id']").attr('checked',t.checked);//改變name名為id的input標簽內的復選框的checked屬性 } function chg(){//當下面的復選框全部選中時,則將第一個復選框設置為選中,當下面的復選框中有一個沒有被選中時,則第一個復選框取消選中; var ids = $.makeArray($("input[name='id']")); for(var i in ids){ if(ids[i].checked==false){//如果所有的復選框只要有一個未選中,則第一個復選框不會選中 $("input[name='ids']").attr('checked', false); return; } } $("input[name='ids']").attr('checked', true);//全部選中的情況下,則第一個復選框選中 } function deleteBatch(){//將下面的復選框的id值傳遞給Controller層,組成id數組,拼接url到controller層,調用批量刪除方法(deleteBatch())方法 var ids = $.makeArray($("input[name='id']:checked"));//通過$.makeArray將id放在數組中 var url = '<%basePath%>/web/goodsList/deleteBatch';//此url指向controller層的deleteBatch方法,需要id屬性 var flag = true; for(var i in ids){//遍歷數組 if(i == 0){ url += "?id=" + ids[i].value;//第一個id屬性前加?拼接 flag = false;  } else { url += "&id=" + ids[i].value;//后面的id屬性前加&拼接 flag = false;  } } if(flag){//如果沒有選中商品 alert("請選中商品!"); return; } if(confirm("確定刪除記錄嗎?")){ window.location.href = url;//把拼接好的id數組傳給頁面 } } </script>

二、在jsp頁面中對應的列表:

1、列表中要給表頭中的復選框(第一個復選框)設置name名,並調用chgAll(this)方法來實現全選或全不選;

2、table中的復選框設置name名,並調用chg()方法來實現上面的第二個功能;

3、form表單提交時調用deleteBatch()方法

<body>
	<form:form id="uuForm" modelAttribute="goods" 	action="<%basePath%>/web/goodsList/" method="post" >//form表單提交時調用deleteBatch()方法
		<div>	<input  type="button"	onclick="deleteBatch()" value="批量刪除" />	</div>
	</form:form>
	<sys:message content="${message}" />
	<table id="cTable" >
		<thead>
			<tr>
			<th><input type="checkbox" name="ids"  onchange="chgAll(this)" /></th>//調用chgAll(this)方法來實現全選或全不選,此處的this指所有復選框對象
				<th>商品編號</th>
				<th>商品標題</th>
			</tr>
		</thead>
		<tbody>
			<c:forEach items="${goods}" var="goods" varStatus="status">
				<tr>
				<td><input type="checkbox"  name="id" value="${goods.goodsId }" onchange="chg()"/></td>//調用chg()方法
					<td>${webGoodsInfo.goodsNo}</td>
					<td>${webGoodsInfo.goodsTitle}</td>
				</tr>
			</c:forEach>
		</tbody>
	</table>
	
</body>

三、看下spring MCV中的controller代碼

@RequestMapping("deleteBatch")//對應jsp頁面中的deleteBatch()請求
	public String deleteBatch(Long[] id, RedirectAttributes redirectAttributes){//此處的id為頁面中的id值,必須保持一直!!!!
		if(id !=null&&id.length!=0){
			goodsService.deleteBatch(id);
		}
		return "redirect:"+Global.getAdminPath()+"/web/webGoodsInfo/?repage";//重定向到列表頁面
	}
}

看下效果:

 

(代碼部分我省略了不少,但是今天講的復選框多選與傳值的部分全部無損呈現!)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM