1. 程式人生 > >使用jQuery實現全選,反選

使用jQuery實現全選,反選

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery-1.6.js"></script>
	</head>

	<body>
		<table border="1" align="center">
			<thead>
				<tr>
					<th>狀態</th>
					<th>使用者名稱</th>
				</tr>
			</thead>
			<tbody>
				<tr>
					<td><input type="checkbox" /></td>
					<td>趙</td>
				</tr>
				<tr>
					<td><input type="checkbox" /></td>
					<td>錢</td>
				</tr>
				<tr>
					<td><input type="checkbox" /></td>
					<td>孫</td>
				</tr>
				<tr>
					<td><input type="checkbox" /></td>
					<td>李</td>
				</tr>
				<tr>
					<td><input type="checkbox" /></td>
					<td>周</td>
				</tr>
			</tbody>
			<tfoot>
				<tr>
					<td>
						<input type="checkbox" /> 全選
					</td>
					<td>
						<input type="button" value="全反選" />
					</td>
				</tr>
			</tfoot>
		</table>

	</body>
	<script type="text/javascript">
		$("tfoot input:checkbox").click(function() {
			var flag = this.checked;
			if(flag) {
				$("tbody input:checkbox").attr("checked", "checked");
			} else {
				$("tbody input:checkbox").removeAttr("checked");
			}
		})
		//全反選
			//定位tfoot標籤中的全反選按鈕,同時新增單擊事件
			$("tfoot input:button").click(function(){
				//將tbody標籤中的所有選中的複選框失效
				$("tbody input:checkbox:checked").attr("disabled","disabled");
				//將tbody標籤中的所有生效的複選框選中
				$("tbody input:checkbox:enabled").attr("checked","checked");
				//將tbody標籤中的所有生效的複選框生效且設定為未選中
				$("tbody input:checkbox:disabled").removeAttr("disabled").removeAttr("checked");
			});
			
	</script>

</html>