萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 核取方塊全選/取消/反選/取值完整範例

HTML 結構

<table id="dataTable" border="1">
  <thead>
    <tr>
      <th><input type="checkbox" id="checkAllToggle"></th>
      <th>ID</th><th>姓名</th><th>電話</th><th>地址</th>
    </tr>
  </thead>
  <tbody>
    <tr><td><input type="checkbox" class="userid" value="1"></td><td>1</td><td>王小明</td><td>18888000</td><td>台北</td></tr>
    <tr><td><input type="checkbox" class="userid" value="2"></td><td>2</td><td>李大華</td><td>18888001</td><td>台中</td></tr>
    <tr><td><input type="checkbox" class="userid" value="3"></td><td>3</td><td>陳美美</td><td>18888002</td><td>高雄</td></tr>
  </tbody>
  <tfoot>
    <tr>
      <td colspan="5">
        <button id="btnSelectAll">全選</button>
        <button id="btnDeselectAll">取消全選</button>
        <button id="btnInvert">反選</button>
        <button id="btnDelete">批次刪除</button>
      </td>
    </tr>
  </tfoot>
</table>

jQuery 互動邏輯

$(function() {
    var $checkboxes = $('.userid');
    var $toggle = $('#checkAllToggle');

    // 1. 表頭核取方塊:全選/取消全選
    $toggle.on('change', function() {
        $checkboxes.prop('checked', this.checked);
    });

    // 2. 列核取方塊變動時同步表頭狀態
    $checkboxes.on('change', function() {
        $toggle.prop('checked', $checkboxes.filter(':checked').length === $checkboxes.length);
        $toggle.prop('indeterminate', $checkboxes.filter(':checked').length > 0 && 
                                     $checkboxes.filter(':checked').length < $checkboxes.length);
    });

    // 3. 全選按鈕
    $('#btnSelectAll').on('click', function() { $checkboxes.prop('checked', true).trigger('change'); });

    // 4. 取消全選
    $('#btnDeselectAll').on('click', function() { $checkboxes.prop('checked', false).trigger('change'); });

    // 5. 反選
    $('#btnInvert').on('click', function() {
        $checkboxes.each(function() { this.checked = !this.checked; }).trigger('change');
    });

    // 6. 批次刪除:取得勾選值
    $('#btnDelete').on('click', function() {
        var ids = $checkboxes.filter(':checked').map(function() { return this.value; }).get();
        if (ids.length === 0) return alert('請至少選擇一筆');
        if (confirm('確定刪除 ' + ids.length + ' 筆資料?')) {
            console.log('送往後端刪除 IDs:', ids);
            // $.post('/api/delete', { ids: ids }, ...)
        }
    });
});

關鍵 API 對照

需求方法說明
設定/取得 checked.prop('checked', true/false)屬性操作用 prop,非 attr
篩選勾選項.filter(':checked')回傳 jQuery 物件
取得值陣列.map(fn).get()轉為原生陣列
半選狀態.prop('indeterminate', true)視覺上顯示「部分選取」

進階:動態新增列時自動綁定

// 使用事件委派
$('#dataTable').on('change', '.userid', function() {
    // 同步表頭邏輯同上
});
copyright © 萬盛學電腦網 all rights reserved