Jquery全選/取消checkbox

發現這個小功能挺普遍,偶爾會用到。特別是在列表操作的時候,寫個Demo。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
  <title>checkBox的全選和取消</title>
	<script src="http://code.jquery.com/jquery-1.4.4.min.js" type="text/javascript"></script>
	<script type="text/javascript">
		jQuery(function(){
			$("#checkAll").click(
				function(){
					if($("#checkAll").attr("checked")==true){
						$("input[name$='item']").attr("checked","true");
						$("#delete").removeAttr("disabled");		
					}else{
						$("input[name$='item']").removeAttr("checked");
						$("#delete").attr("disabled","disabled");
					}
				}
			);
			$("input[name$='item']").click(
				function(){
					var $chk = $("[name = item]:checkbox");
					if($(this).attr("checked")==true){
						$("#delete").removeAttr("disabled");	
					}
					else{
						if($("input:checked[name$='item']").length==0){
							$("#delete").attr("disabled","disabled");
						}
					}
					$("#checkAll").attr("checked", $chk.length == $chk.filter(":checked").length);	
				}
			);
		});
	</script>
  </head>
  <body>
		<div>
		<input type="button" id="delete" name="delete" value="刪除" disabled="disabled">
			<table id="gvData" border="1" cellspacing="1">
				<thead >
					<tr>
						<th>
							<input id="checkAll" name="checkAll" type="checkbox"/>
						</th>
						<th>車牌號</th>
						<th>起運地</th>
						<th>目的地</th>
					</tr>
				</thead>
				<tbody>	
						<tr>
							<td><input id="001" name="item" type="checkbox"/></td>
							<td>浙A898800</td>
							<td>寧波</td>
							<td>杭州</td>
						<tr/>
						<tr>
							<td><input id="002" name="item" type="checkbox"/></td>
							<td>浙A898800</td>
							<td>寧波</td>
							<td>杭州</td>
						<tr/>
						<tr>
							<td><input id="003" name="item" type="checkbox"/></td>
							<td>浙A898800</td>
							<td>寧波</td>
							<td>杭州</td>
						<tr/>
						<tr>
							<td><input id="004" name="item" type="checkbox"/></td>
							<td>浙A898800</td>
							<td>寧波</td>
							<td>杭州</td>
						<tr/>
				</tbody>
			</table>
		</div>
  </body>
</html>


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章