批次操作時常需要把勾選的項目收集成一個字串,再塞進隱藏欄位一起送出。以下是完整寫法。
jQuery(function ($) {
$("input[name='key']:checkbox").click(function () {
var ids = '';
var flag = 0;
$("#ids").attr("value", ids);
$("input[name='key']:checkbox").each(function () {
if (true == $(this).attr("checked")) {
ids += $(this).attr('value') + ',';
flag += 1;
}
});
if (0 < flag) {
$("#ids").attr("value", ids);
return true;
} else {
alert('請至少選擇一項!');
return false;
}
});
});
取得 name='key' 的複選框值,將選中項的 value 以逗號串接,寫到隱藏域中:
<input type="hidden" name="ids" id="ids" value="" />
$("input[name='key']:checkbox").each(function () {
if (true == $(this).attr("checked")) {
ids += $(this).attr('value') + ',';
}
});
在 HTML 中,如果一個複選框被選中,對應的標記為 checked="checked"。但如果用 jQuery 讀 $("#id").attr("checked"),則會提示您是 "true" 而不是 "checked",所以判斷 if("checked" == $("#id").attr("checked")) 是錯誤的,應該如上面那樣書寫:
if (true == $("#id").attr("checked")) { ... }
更根本的解法是改用專門表示狀態的 API:$(this).prop("checked") 或直接用原生屬性 this.checked。attr 反映的是 HTML 初始標記,prop 反映的是目前狀態,兩者混用正是這類 bug 的來源。
另外,串接完記得去掉最後多餘的逗號(ids.slice(0, -1));用 map + join 會更乾淨:
var ids = $("input[name='key']:checked").map(function () {
return this.value;
}).get().join(',');