Checkbox

ฟังก์ชัน checkbox select all & uncheck

เวลาที่กด select all เเล้วไปเลือก unchecked ออก 1 ตัว ตรงที select all จะต้อง unchecked ด้วย มาดูโค้ดกัน ^^

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Check All</title>
<style>
a small {
	color:#0033ff;
}
</style>
</head>
<body>
<a title="Filter Category" id="general">
	<i>
		<strong>Count the checkboxes</strong>: <small class="counter"></small> <strong>Foo</strong>: <small class="counter-foo"></small> <strong>Bar</strong>: <small class="counter-bar"></small>
	</i>
</a>
<div id="video-filter-container">
	<div id="general-content">
		<ul>
			<li class="checkbox-foo category">
				<label><input type="checkbox" class="select_all" /> Select All </label>
				<ul>
					<li><input value="11" type="checkbox" name="wpmm[]" checked /> Foo1</li>
					<li><input value="12" type="checkbox" name="wpmm[]" /> Foo2</li>
				</ul>
			</li>
			<li class="checkbox-bar category">
				<label><input type="checkbox" class="select_all" /> Select All</label>
				<ul>
					<li><input value="21" type="checkbox" name="wpmm[]" /> Bar1</li>
					<li><input value="22" type="checkbox" name="wpmm[]" /> Bar2</li>
					<li><input value="23" type="checkbox" name="wpmm[]" /> Bar3</li>
				</ul>
			</li>
		</ul>
	</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script>
function updateCounter() {
	let allChecked = $('#general-content input[name="wpmm[]"]:checked').length;
	if (allChecked > 0) {
		$("#general i .counter").text('(' + allChecked + ')');
	} else {
		$("#general i .counter").text('');
	}
	updateCounterFor('foo');
	updateCounterFor('bar');
}
function updateCounterFor(part = 'foo') {
	let partChecked = $('#general-content .checkbox-' + part + ' input[name="wpmm[]"]:checked').length;
	if (partChecked > 0) {
		$('#general i .counter-' + part).text('(' + partChecked + ')');
	} else {
		$('#general i .counter-' + part).text('');
	}
}
$(function () {
	$("#general i .counter").text('');
	$('#general i .counter-foo, #general i .counter-bar').text('');
	updateCounter();
	$(".select_all").change(function () {
		let thisCheckbox = $(this);
		let checkboxes = thisCheckbox.parent().next("ul").find("input[name='wpmm[]']");
		if (thisCheckbox.is(":checked")) {
			checkboxes.prop('checked', true);
		} else {
			checkboxes.prop('checked', false);
		}
		updateCounter();
	});
	$("#general-content input:checkbox").on("change", function () {
		let parent = $(this).closest("li.category");
		updateCounter();
		if(parent.find("input[name='wpmm[]']:checked").length == parent.find("input[name='wpmm[]']").length) {
			parent.find(".select_all").prop("checked", true);
		} else {
			parent.find(".select_all").prop("checked", false);
		}
	});
});
</script>
</body>
</html>