萬盛學電腦網

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

jQuery 偵測 Checkbox 是否被勾選的最佳寫法

核心方法對比

寫法回傳值推薦度說明
$("input").prop("checked")true/false⭐⭐⭐⭐⭐直接讀取 Property,標準、快速
$("input").is(":checked")true/false⭐⭐⭐⭐語意清晰,內部用 matches 選擇器
$("input").attr("checked")"checked"/undefined❌ 不推薦讀取 Attribute(初始值),不反映即時狀態
element.checkedtrue/false⭐⭐⭐⭐⭐原生最快,零依賴

完整範例

<input type="checkbox" id="agree" name="agree">
<label for="agree">我同意條款</label>
<button id="checkBtn">檢測狀態</button>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$("#checkBtn").on("click", function() {
    // 方法 1:prop(推薦)
    const byProp = $("#agree").prop("checked");

    // 方法 2:is(':checked')
    const byIs = $("#agree").is(":checked");

    // 方法 3:原生(最快)
    const native = document.getElementById("agree").checked;

    console.log({byProp, byIs, native}); // 三者結果一致
    alert(`prop: ${byProp}, is: ${byIs}, native: ${native}`);
});
</script>

批次獲取多個勾選值

<input type="checkbox" name="fruit" value="apple"> 蘋果
<input type="checkbox" name="fruit" value="banana"> 香蕉
<input type="checkbox" name="fruit" value="orange"> 橘子
<button id="getValues">獲取勾選值</button>

<script>
$("#getValues").on("click", () => {
    // jQuery map + get
    const vals = $("input[name='fruit']:checked").map((i, el) => el.value).get();
    // 或原生
    // const vals = [...document.querySelectorAll("input[name='fruit']:checked")].map(el => el.value);
    console.log(vals); // ["apple", "orange"]
    alert("勾選:" + vals.join(", ") || "無");
});
</script>

全選/反選/奇數選實作

$("#selectAll").on("click", () => $("input[name='fruit']").prop("checked", true));
$("#deselectAll").on("click", () => $("input[name='fruit']").prop("checked", false));
$("#selectOdd").on("click", () => $("input[name='fruit']:even").prop("checked", true)); // :even = 索引 0,2,4... (第 1,3,5 項)
$("#invert").on("click", () => $("input[name='fruit']").prop("checked", (i, v) => !v));

避坑指南

  • **永遠用 prop() 設定/讀取 checked、disabled、selected 等布林屬性。**
  • attr("checked", "checked") 僅設定初始 HTML 屬性,**不改變視覺狀態**。
  • 動態新增 checkbox 後,事件委派用 $(document).on("change", "input[type='checkbox']", handler)。
copyright © 萬盛學電腦網 all rights reserved