萬盛學電腦網

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

jQuery 判斷 Checkbox 是否勾選:.is(':checked') 與 .prop('checked') 正確用法

最推薦寫法

// 回傳 true / false(布林值)
const isChecked = $('#field_systemBackup').is(':checked');
// 或
const isChecked = $('#field_systemBackup').prop('checked');

三種常見寫法對比

寫法回傳值優點缺點
$('#cb').is(':checked') true / false 語意明確、鏈式呼叫友善 需解析選擇器,極微效能差異
$('#cb').prop('checked') true / false 直接存取 DOM property、效能最佳 需記得用 prop 而非 attr
$('#cb').attr('checked') "checked" / undefined jQuery 1.6 前常用 **錯誤**:反映初始 HTML 屬性,非即時狀態
$('#cb')[0].checked true / false 原生 DOM、零依賴 需取得原生元素 [0]
document.getElementById('cb').checked true / false 原生、最快 無 jQuery 鏈式風格

完整互動範例

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Checkbox 狀態判斷</title>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
  <label><input type="checkbox" id="agree"> 我同意條款</label>
  <button id="submitBtn" disabled>送出</button>
  <p id="status">狀態:未勾選</p>

  <script>
    const $cb = $('#agree');
    const $btn = $('#submitBtn');
    const $status = $('#status');

    $cb.on('change', function () {
      const checked = $cb.prop('checked'); // 或 this.checked
      $btn.prop('disabled', !checked);
      $status.text('狀態:' + (checked ? '已勾選' : '未勾選'));
    });

    // 表單送出前最終驗證
    $('#submitBtn').click(function () {
      if (!$cb.is(':checked')) {
        alert('請先同意條款');
        return false;
      }
      alert('送出成功!');
    });
  </script>
</body>
</html>

進階:多選框群組處理

<div id="fruits">
  <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="orange"> 橘子</label>
</div>
<button id="getSelected">取得已選</button>

<script>
$('#getSelected').click(() => {
  // 取得所有被勾選的值陣列
  const selected = $('input[name="fruit"]:checked').map((i, el) => el.value).get();
  // 或原生
  // const selected = [...document.querySelectorAll('input[name="fruit"]:checked')].map(el => el.value);
  console.log(selected); // ['apple', 'orange'] 等
  alert('已選:' + selected.join(', '));
});
</script>

總結

  • 單一 checkbox 判斷:.prop('checked') 最標準、效能最好。
  • 篩選多個 checkbox::checked 偽類選擇器配合 .map()。
  • 絕對避免 .attr('checked') 判斷即時狀態。
  • 表單提交前:用 FormData 自動收集,或手動驗證 required 屬性。
copyright © 萬盛學電腦網 all rights reserved