表單中有多組核取方塊(Group A、Group B),組內核取方塊需「全選/全不選」聯動:勾選任一,組內其餘同步勾選;取消任一,組內其餘同步取消。
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head><meta charset="utf-8"><title>jQuery 核取方塊群組聯動</title>
<script src="/js/jquery-1.6.2.min.js"></script>
<script>
$(function() {
// A 組聯動
var $classA = $(".classA");
$classA.change(function() {
var checked = $(this).prop("checked"); // 使用 prop 取得布林值
$classA.prop("checked", checked);
});
// B 組聯動
var $classB = $(".classB");
$classB.change(function() {
var checked = $(this).prop("checked");
$classB.prop("checked", checked);
});
});
</script></head>
<body>
<p>A 組</p>
<input type="checkbox" class="classA"> 選項 A1
<input type="checkbox" class="classB"> 選項 A2
<p>B 組</p>
<input type="checkbox" class="classB"> 選項 B1
<input type="checkbox" class="classB"> 選項 B2
</body></html>
| 屬性 | prop() | attr() |
|---|---|---|
checked | ✅ 返回 boolean (true/false) | ❌ 返回 "checked" 或 undefined |
disabled | ✅ boolean | ❌ 字串 |
selected | ✅ boolean | ❌ 字串 |
value | 當前值 | 初始 HTML 屬性值 |
鐵律:表單元素固有屬性 (checked, disabled, selected, value) 一律用.prop();自訂屬性、HTML 標籤屬性用.attr()。
$(document).on('change', '.group-checkbox', function() {
var $group = $('.' + $(this).data('group'));
$group.prop('checked', $(this).prop('checked'));
});
// HTML:
<input type="checkbox" id="selectAllA"> 全選/取消 A 組
<script>
$("#selectAllA").change(function() {
$(".classA").prop("checked", this.checked);
});
</script>
核心邏輯極簡:change 事件 → 讀取觸發源 checked 狀態 → 寫入同群組所有元素。記住用 .prop() 處理布林屬性,避免 .attr() 導致的「永遠為真」或「無法取消」Bug。