Checkbox 組處理是表單開發高頻需求。本文深度解析 jQuery 遍歷獲取選中值的核心邏輯、正確判斷選中狀態的方法、隱藏域同步技巧及現代化改進方案。
// 核心:遍歷 name='key' 的 checkbox
var ids = "";
var flag = 0;
$("input[name='key']:checkbox").each(function() {
// 關鍵:正確判斷選中狀態
if (true === $(this).prop("checked")) { // 或 this.checked
ids += $(this).val() + ",";
flag++;
}
});
// 寫入隱藏域
$("#ids").val(ids);
// 驗證至少選一項
if (flag === 0) {
alert("請至少選擇一項!");
return false;
}
return true;
| 方式 | 代碼 | 返回值 | 推薦度 |
|---|---|---|---|
| prop (推薦) | `$(this).prop("checked")` | true/false | ⭐⭐⭐⭐⭐ |
| 原生屬性 (最快) | `this.checked` | true/false | ⭐⭐⭐⭐⭐ |
| attr (jQuery < 1.6) | `$(this).attr("checked")` | "checked"/undefined | ❌ 已棄用 |
| is 選擇器 | `$(this).is(":checked")` | true/false | ⭐⭐⭐⭐ |
原文錯誤提醒:原文稱 `attr("checked")` 返回 `"true"` 字符串,實際 jQuery 1.6+ 返回 `undefined`(未選中)或 `"checked"`(選中),絕不可用 `== "checked"` 或 `== true` 判斷。
// ✅ 推薦:val() 自動處理無 value 時返回文本
$(this).val();
// ⚠️ attr 只獲取屬性值,無 value 屬性時返回 undefined
$(this).attr("value");
var values = $("input[name='key']:checkbox:checked")
.map(function() { return this.value; })
.get(); // ["val1", "val2", ...]
// ES6 箭頭函數
var values = $("input[name='key']:checked").map((i, el) => el.value).get();
var checkboxes = document.querySelectorAll("input[name='key']:checked");
var values = Array.from(checkboxes, el => el.value);
// 或
var values = [...checkboxes].map(el => el.value);
var formData = new FormData(document.getElementById("myForm"));
// 多選框同名會自動追加多個條目
// 後端接收數組/List
// 或手動構建
var formData = new FormData();
$("input[name='key']:checked").each(function() {
formData.append("key", this.value);
});
$.fn.checkboxValues = function(options) {
var opts = $.extend({
separator: ",", // 字符串分隔符
target: null, // 同步目標選擇器 (如 "#ids")
minSelect: 0, // 最小選擇數
maxSelect: Infinity, // 最大選擇數
onChange: null // 變化回調
}, options);
var $checkboxes = this.filter(":checkbox");
var $target = opts.target ? $(opts.target) : $();
function collect() {
var values = $checkboxes.filter(":checked").map(function() {
return this.value;
}).get();
// 同步隱藏域
if ($target.length) {
$target.val(values.join(opts.separator));
}
// 驗證
var valid = values.length >= opts.minSelect && values.length <= opts.maxSelect;
// 回調
if (opts.onChange) {
opts.onChange(values, valid);
}
return {values: values, valid: valid, string: values.join(opts.separator)};
}
// 綁定變化事件
$checkboxes.on("change", collect);
// 初始收集
return collect();
};
// 使用示例
$("input[name='key']").checkboxValues({
target: "#ids",
minSelect: 1,
onChange: function(values, valid) {
$("#submit-btn").prop("disabled", !valid);
console.log("選中:", values);
}
});
// 全選
$("#check-all").on("change", function() {
$("input[name='key']:checkbox").prop("checked", this.checked);
});
// 獲取未選中項
var unchecked = $("input[name='key']:checkbox:not(:checked)").map(function() {
return this.value;
}).get();
// 設置指定值選中
function checkValues(values) {
var valSet = new Set(values);
$("input[name='key']:checkbox").prop("checked", function() {
return valSet.has(this.value);
});
}
掌握正確的選中判斷、現代化獲取方式與封裝模式,Checkbox 組處理將不再是樣板代碼重災區。