延續上一篇,本文示範以**按鈕**而非核取方塊觸發全選/反選/全不選的常見模式,並處理動態新增列、表單提交序列化等實務細節。
<fieldset>
<legend>水果選擇</legend>
<div id="fruit-list">
<label><input type="checkbox" name="fruit" value="apple"> 蘋果</label>
<label><input type="checkbox" name="fruit" value="banana"> 香蕉</label>
<label><input type="checkbox" name="fruit" value="pineapple"> 鳳梨</label>
<label><input type="checkbox" name="fruit" value="strawberry"> 草莓</label>
<label><input type="checkbox" name="fruit" value="pear"> 梨子</label>
</div>
<div class="actions">
<button type="button" id="btn-select-all">全選</button>
<button type="button" id="btn-invert">反選</button>
<button type="button" id="btn-select-none">全不選</button>
</div>
</fieldset>
(function($) {
const $list = $('#fruit-list');
const $checkboxes = () => $list.find('input[name="fruit"]'); // 函式取得最新集合
// 全選
$('#btn-select-all').on('click', function() {
$checkboxes().prop('checked', true);
});
// 全不選
$('#btn-select-none').on('click', function() {
$checkboxes().prop('checked', false);
});
// 反選
$('#btn-invert').on('click', function() {
$checkboxes().each(function() {
this.checked = !this.checked; // 原生 DOM 操作最快
});
});
// 動態新增項目示範
$('#btn-add').on('click', function() {
const newVal = 'fruit-' + Date.now();
$list.append(``);
});
// 表單提交:取得所有勾選值
$('#submit-form').on('submit', function(e) {
e.preventDefault();
const selected = $checkboxes().filter(':checked').map(function() {
return this.value;
}).get();
console.log('提交資料:', selected);
// $.ajax({ data: { fruits: selected } });
});
})(jQuery);
const unselected = $checkboxes().not(':checked').map(function() {
return this.value;
}).get();
this.checked = ... 原生屬性存取,避免 jQuery 封裝開銷。$checkboxes().trigger('change')。IntersectionObserver。type="button" 防止誤觸發表單提交。aria-label 或可見文字說明按鈕功能。const list = document.getElementById('fruit-list');
const getCheckboxes = () => list.querySelectorAll('input[name="fruit"]');
document.getElementById('btn-select-all').addEventListener('click', () => {
getCheckboxes().forEach(cb => cb.checked = true);
});
document.getElementById('btn-invert').addEventListener('click', () => {
getCheckboxes().forEach(cb => cb.checked = !cb.checked);
});
document.getElementById('btn-select-none').addEventListener('click', () => {
getCheckboxes().forEach(cb => cb.checked = false);
});
按鈕觸發模式在「批次操作工具列」場景極常見,掌握核心邏輯與無障礙細節,即可快速套用至各類管理後台。