Checkbox 群組的全選、反選、獲取選中值是表單處理的高頻需求。本文提供 jQuery 與原生 JS 兩套實作,涵蓋動態列表、不可用狀態、表單提交序列化、Indeterminate 狀態同步等實戰細節。
// 全選
function checkAll() {
$('input[name="TheID"]').prop('checked', true);
}
// 反選
function uncheckAll() {
$('input[name="TheID"]').each(function() {
this.checked = !this.checked;
});
}
// 獲取選中值 (陣列)
function getCheckedValues() {
return $('input[name="TheID"]:checked').map(function() {
return $(this).val();
}).get(); // 返回原生陣列
}
// 獲取選中值 (逗號分隔字串)
function getCheckedValuesCsv() {
return getCheckedValues().join(',');
}
// 全選框聯動 (Indeterminate 狀態)
$('#selectAll').on('change', function() {
$('input[name="TheID"]').prop('checked', this.checked);
});
$('input[name="TheID"]').on('change', function() {
const $all = $('input[name="TheID"]');
const $checked = $all.filter(':checked');
$('#selectAll').prop({
checked: $checked.length === $all.length,
indeterminate: $checked.length > 0 && $checked.length < $all.length
});
});
class CheckboxGroup {
constructor(name, container = document) {
this.name = name;
this.container = container;
this.selectAllEl = container.querySelector(`[data-select-all="${name}"]`);
this._bindEvents();
}
_getCheckboxes() {
return Array.from(this.container.querySelectorAll(`input[name="${this.name}"][type="checkbox"]`));
}
_bindEvents() {
if (this.selectAllEl) {
this.selectAllEl.addEventListener('change', () => this.toggleAll(this.selectAllEl.checked));
}
// 事件委派:動態新增的 checkbox 也生效
this.container.addEventListener('change', (e) => {
if (e.target.matches(`input[name="${this.name}"][type="checkbox"]`)) {
this._updateSelectAllState();
}
});
}
// 全選/取消全選
toggleAll(checked) {
this._getCheckboxes().forEach(cb => {
if (!cb.disabled) cb.checked = checked;
});
this._updateSelectAllState();
}
// 反選
invert() {
this._getCheckboxes().forEach(cb => {
if (!cb.disabled) cb.checked = !cb.checked;
});
this._updateSelectAllState();
}
// 獲取選中值陣列
getCheckedValues() {
return this._getCheckboxes()
.filter(cb => cb.checked)
.map(cb => cb.value);
}
// 獲取選中元素陣列
getCheckedElements() {
return this._getCheckboxes().filter(cb => cb.checked);
}
// 同步全選框狀態
_updateSelectAllState() {
if (!this.selectAllEl) return;
const boxes = this._getCheckboxes();
const checked = boxes.filter(cb => cb.checked);
this.selectAllEl.checked = checked.length === boxes.length && boxes.length > 0;
this.selectAllEl.indeterminate = checked.length > 0 && checked.length < boxes.length;
}
// 設置選中值 (回顯)
setCheckedValues(values) {
const valueSet = new Set(values);
this._getCheckboxes().forEach(cb => {
cb.checked = valueSet.has(cb.value);
});
this._updateSelectAllState();
}
}
// 使用
const group = new CheckboxGroup('TheID', document.getElementById('form'));
group.toggleAll(true); // 全選
group.invert(); // 反選
console.log(group.getCheckedValues()); // ['val1', 'val2']
group.setCheckedValues(['val1', 'val3']); // 回顯
<form id="form">
<label><input type="checkbox" data-select-all="TheID" /> 全選</label>
<div class="item-list">
<label><input type="checkbox" name="TheID" value="1" /> 項目 1</label>
<label><input type="checkbox" name="TheID" value="2" /> 項目 2</label>
<label><input type="checkbox" name="TheID" value="3" disabled /> 項目 3 (禁用)</label>
</div>
<button type="button" onclick="console.log(group.getCheckedValues())">獲取選中</button>
</form>
// jQuery
$('#form').serialize(); // "TheID=1&TheID=2&TheID=3" (同名多值)
// 或
$('#form').serializeArray(); // [{name: 'TheID', value: '1'}, ...]
// 原生
const formData = new FormData(document.getElementById('form'));
const values = formData.getAll('TheID'); // ['1', '2', '3']
// fetch 提交
fetch('/api/submit', { method: 'POST', body: new FormData(form) });
| 場景 | 處理策略 |
|---|---|
| 動態新增/刪除 checkbox | 事件委派 + 類封裝自動獲取最新列表 |
| 分頁表格跨頁全選 | 維護 Set 記錄全選 ID,分頁載入時回顯 |
| 巢狀樹形結構 | 父子聯動:父選中 → 子全選;子全選 → 父 indeterminate |
| 大量數據 (虛擬列表) | 只渲染可視區,選中狀態存於資料模型 |
| 防止表單重複提交 | 提交時 disabled 全部 checkbox + 按鈕 |