Checkbox 狀態完全由 HTMLInputElement.checked 布爾屬性控制:
true = 選中false = 未選中// 方式 1:原生 DOM
const checkbox = document.getElementById('myCheckbox');
const isChecked = checkbox.checked; // true / false
// 方式 2:jQuery(返回首個匹配元素的屬性值)
const isChecked = $('#myCheckbox').prop('checked'); // 推薦用 .prop() 而非 .attr()
const isChecked = $('#myCheckbox').is(':checked'); // 語義化寫法
// 原生
checkbox.checked = true; // 選中
checkbox.checked = false; // 取消選中
// jQuery
$('#myCheckbox').prop('checked', true); // 選中
$('#myCheckbox').prop('checked', false); // 取消選中
// 切換狀態
checkbox.checked = !checkbox.checked;
// 或
$('#myCheckbox').prop('checked', i => !i); // 函數式切換
<label>
<input type="checkbox" id="agree"> 我同意條款
</label>
<button id="submit" disabled>提交</button>
<script>
const $agree = $('#agree');
const $submit = $('#submit');
$agree.on('change', function() {
$submit.prop('disabled', !this.checked);
});
// 表單提交前驗證
$('#form').on('submit', function(e) {
if (!$agree.prop('checked')) {
alert('請同意條款');
e.preventDefault();
}
});
</script>
| 錯誤寫法 | 問題 | 正確寫法 |
|---|---|---|
$('#cb').attr('checked') | 返回初始 HTML 屬性,不反映當前狀態 | .prop('checked') 或 .is(':checked') |
checkbox.checked = 'true' | 字串非空即 truthy,永遠為 true | checkbox.checked = true (布爾值) |
if (checkbox.value) | value 屬性不隨勾選變化,默認 "on" | if (checkbox.checked) |
<table>
<thead><tr><th><input type="checkbox" id="checkAll"></th>...</tr></thead>
<tbody>
<tr><td><input type="checkbox" class="rowCheck" value="1"></td>...</tr>
<tr><td><input type="checkbox" class="rowCheck" value="2"></td>...</tr>
</tbody>
</table>
<script>
const $checkAll = $('#checkAll');
const $rowChecks = $('.rowCheck');
// 全選/取消全選
$checkAll.on('change', function() {
$rowChecks.prop('checked', this.checked);
});
// 行勾選變化更新全選狀態
$rowChecks.on('change', function() {
$checkAll.prop('checked', $rowChecks.length === $rowChecks.filter(':checked').length);
});
// 獲取所有選中值
function getSelectedIds() {
return $rowChecks.filter(':checked').map((i, el) => el.value).get(); // ["1", "2"]
}
</script>
Checkbox 狀態核心就是 .checked 布爾屬性。記住三點:
.checked / .prop('checked'),別用 .attr() / .value.prop() 配合 :checked 選擇器這是表單交互的基石,掌握它,複雜的全選、級聯、驗證邏輯都能輕鬆構建。