1. 程式人生 > >jQuery實現全選和反選

jQuery實現全選和反選

<!DOCTYPE html>
<html>
<head>
<title>MyHtml.html</title>

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script type="text/javascript">
	$(function() {
		//全選
		$("#all").click(function() {

			var flag = $(this).attr("checked");
			$("[name=loves]").attr("checked", flag == "checked");
		});

		//反選
		$("#reverse").click(function() {

			$("[name=loves]").each(function() {
				var flag = $(this).attr("checked");
				$(this).attr("checked", !(flag == "checked"));
			});
			checkSelect();
		});

		$("[name=loves]").click(function() {

			checkSelect();
		});

		function checkSelect() {
			var allFlag = true;
			$("[name=loves]").each(function() {
				var flag = $(this).attr("checked") == "checked";

				allFlag = allFlag && flag;
			});
			$("#all").attr("checked", allFlag);
		}

	});
</script>
</head>

<body>
  <div>
  愛好:
	<input type="checkbox" id="all">全選     
	<input type="checkbox" id="reverse">反選
	<br />
	<input type="checkbox" name="loves" />吃
	<input type="checkbox" name="loves"/>喝
	<input type="checkbox" name="loves" />玩
	<input type="checkbox" name="loves"/>樂
	<br>
</div>
</body>
</html>