萬盛學電腦網

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

jQuery 獲取復選框(Checkbox)選中值的多種方法與最佳實踐

表單處理中獲取「被選中的復選框值」是高頻操作。本文總結 jQuery 多種選取寫法、值收集策略、全選/反選/狀態判斷完整工具函數,並指出常見陷阱。

基礎選取器寫法

<input type="checkbox" name="checkbox" value="1" />
<input type="checkbox" name="checkbox" value="2" checked />
<input type="checkbox" name="checkbox" value="3" />

// 1. 屬性選擇器 (推薦,語義明確)
$("input[name='checkbox']:checked")          // 最標準
$("input[name='checkbox'][checked]")         // 老版本寫法,僅匹配靜態 checked 屬性,動態勾選無效 ❌

// 2. 過濾器方法
$("input[name='checkbox']").filter(":checked")

// 3. 原生 DOM 循環 (性能最優,無 jQuery 開銷)
var checked = [];
document.querySelectorAll("input[name='checkbox']:checked").forEach(function(el){
    checked.push(el.value);
});

收集選中值為字符串/數組

// 需求:將選中值用逗號拼接填入文本框
$("#btn5").click(function(){
    var vals = $("input[name='checkbox']:checked").map(function(){
        return this.value; // this 指向原生 DOM
    }).get().join(","); // .get() 轉原生數組,join 拼接
    
    $("#dd").val(vals);
});

// 獲取數組 (便於後續處理)
var arr = $("input[name='checkbox']:checked").map(function(){ return this.value; }).get();
// arr = ["2"] (示例中只有 value=2 被選中)

全選 / 反選 / 狀態判斷工具函數

var CheckboxUtil = {
    // 全選
    checkAll: function(name, flag) {
        flag = (flag !== false); // 默認 true
        $("input[name='" + name + "']").prop("checked", flag);
    },
    // 反選
    toggleAll: function(name) {
        $("input[name='" + name + "']").each(function(){
            this.checked = !this.checked; // 原生屬性切換最快
        });
    },
    // 獲取選中值數組
    getCheckedValues: function(name) {
        return $("input[name='" + name + "']:checked").map(function(){ return this.value; }).get();
    },
    // 判斷是否全選
    isAllChecked: function(name) {
        var $items = $("input[name='" + name + "']");
        return $items.length > 0 && $items.filter(":checked").length === $items.length;
    },
    // 判斷是否至少選一項
    hasChecked: function(name) {
        return $("input[name='" + name + "']:checked").length > 0;
    }
};

// 使用
CheckboxUtil.checkAll("checkbox");        // 全選
CheckboxUtil.toggleAll("checkbox");       // 反選
var vals = CheckboxUtil.getCheckedValues("checkbox"); // ["2", "3"]
console.log(CheckboxUtil.isAllChecked("checkbox"));   // false
console.log(CheckboxUtil.hasChecked("checkbox"));     // true

常見坑點與避坑指南

錯誤寫法問題正確寫法
$("input[name='cb']").attr("checked", true)attr 只修改 HTML 屬性,不改變 DOM property,導致 UI 不更新、提交值錯誤.prop("checked", true) (jQuery 1.6+)
$("input[name='cb']:checked").val()只返回**第一個**選中值用 .map().get() 獲取所有
$("input[name='cb'][checked]")僅匹配頁面初始渲染時帶 checked 屬性的,用戶後續點選無效用 :checked 偽類選擇器
在 change 事件中用 this.value 獲取「新選中值」單個 checkbox 觸發 change 時,this.checked 已是新狀態,值固定為 value 屬性,無歧義。但多選框需遍歷統一用 $("input[name='cb']:checked").map(...)

現代原生 JS 寫法 (無 jQuery 依賴)

// 獲取選中值數組
const getCheckedValues = (name) => 
    [...document.querySelectorAll(`input[name="${name}"]:checked`)].map(el => el.value);

// 全選
const checkAll = (name, flag = true) => 
    document.querySelectorAll(`input[name="${name}"]`).forEach(el => el.checked = flag);

// 事件委託:父容器監聽 change
document.getElementById('form').addEventListener('change', e => {
    if (e.target.matches('input[type="checkbox"][name="cb"]')) {
        console.log('單個變化:', e.target.value, e.target.checked);
        // 如需即時獲取所有選中值
        const all = getCheckedValues('cb');
    }
});

掌握 :checked、.prop()、.map().get() 組合拳,能高效、無 Bug 處理復選框交互,是表單開發必備技能。

copyright © 萬盛學電腦網 all rights reserved