// 所有 checkbox
$('input:checkbox')
// 或
$('input[type="checkbox"]')
$('input:checkbox:checked').val();
// 或指定 name
$('input[name="ck"]:checked').val();
var vals = [];
$('input:checkbox:checked').each(function() {
vals.push($(this).val());
});
console.log(vals); // ['v1', 'v2', ...]
// 正確:用 prop
$('input:checkbox:first').prop('checked', true);
// 或
$('input:checkbox').eq(0).prop('checked', true);
// 注意:原文寫錯用了 :radio,此處修正
$('input:checkbox:last').prop('checked', true);
// 索引 2 (第3個)
$('input:checkbox').eq(2).prop('checked', true);
// 範圍:索引 1-2 (第2、3個)
$('input:checkbox').slice(1, 3).prop('checked', true);
// 前兩個
$('input:checkbox').slice(0, 2).prop('checked', true);
$('input:checkbox[value="1"]').prop('checked', true);
$('input:checkbox[value="1"]').remove();
// 刪除第 3 個 (索引 2)
$('input:checkbox').eq(2).remove();
$('input:checkbox').each(function(index, domEle) {
// index: 索引, domEle: 原生 DOM
console.log(index, this.value, this.checked);
});
// 方式一:each
$('input:checkbox').each(function() { this.checked = true; });
// 方式二:prop(推薦,性能更好)
$('input:checkbox').prop('checked', true);
$('input:checkbox').prop('checked', false);
jQuery 1.6+ 強制要求:布爾屬性(checked, disabled, selected, readonly)必須用 .prop(),不能用 .attr()。
// ❌ 錯誤(舊版可行,新版失效/異常)
$('input:checkbox').attr('checked', true);
$('input:checkbox').attr('checked', 'checked');
// ✅ 正確
$('input:checkbox').prop('checked', true);
$('input:checkbox').prop('checked', false);
// 判斷是否選中
var isChecked = $('input:checkbox').prop('checked'); // true/false
// 或
var isChecked = $('input:checkbox').is(':checked'); // true/false
<input type="checkbox" id="checkAll" /> 全選/反選
<div id="list">
<label><input type="checkbox" value="1" /> 項目 1</label><br>
<label><input type="checkbox" value="2" /> 項目 2</label><br>
<label><input type="checkbox" value="3" /> 項目 3</label>
</div>
<script>
$('#checkAll').on('change', function() {
$('#list input:checkbox').prop('checked', this.checked);
});
$('#list input:checkbox').on('change', function() {
var $all = $('#list input:checkbox');
var $checked = $all.filter(':checked');
$('#checkAll').prop('checked', $all.length === $checked.length);
$('#checkAll').prop('indeterminate', $checked.length > 0 && $checked.length < $all.length);
});
</script>