做專案時經常會遇到需要處理 checkbox 全選、反選與收集勾選值的情況。網上範例很多,這裡分享的是我常用的一套寫法。
// js:數值是否在陣列中
Array.prototype.in_array = function(e) {
for (i = 0; i < this.length; i++) {
if (this[i] == e)
return true;
}
return false;
}
// js:陣列 index
Array.prototype.find_str = function(string) {
var str = this.join("");
return str.indexOf(string);
}
var houseIds = new Array();
$("#chebox-list-all").click(function() {
if ($("#chebox-list-all").attr("checked")) {
$("[name='checkboxes']").attr("checked", 'true'); // 全選,收集 id
var ids = document.getElementsByName('checkboxes');
var value = new Array();
for (var i = 0; i < ids.length; i++) {
if (ids[i].checked)
houseIds.push(ids[i].value);
}
alert(houseIds);
} else {
$("[name='checkboxes']").removeAttr("checked"); // 反選,清空 id
houseIds = [];
alert(houseIds);
}
})
// 單選增加 id
function check(obj) {
if (!houseIds.in_array(obj.value)) {
houseIds.push(obj.value);
alert(houseIds);
} else {
var index = houseIds.find_str(obj.value);
houseIds.splice(index, 1);
alert(houseIds);
}
}
全選的 onclick 綁在最上方的「全選」checkbox 上:勾選時把所有 name="checkboxes" 的項目設為 checked,並遍歷收集它們的 value 進 houseIds;取消勾選時清除所有選取狀態並清空陣列。單獨勾選某項時則由 check(obj) 處理,透過 in_array 判斷該值是否已在陣列中,做 toggle 效果。
Array.prototype.indexOf(ES5 起標準支援)與 Array.prototype.includes(ES2016)已經能勝任這件事,不必擴充原生原型。擴充 prototype 有污染全域的風險,團隊協作時容易衝突。join("") 把陣列串成字串再 indexOf,當元素為 "1" 與 "11" 時會誤判——搜尋 "1" 會找到 "11" 的位置。改用 indexOf 直接比對元素才是正確做法。prop() 而非 attr(),否則在部分版本中會出現狀態不同步的問題。var ids = $("[name='checkboxes']:checked").map(function(){ return this.value; }).get();這份範例的價值在於把「收集 → 判斷 → 增刪」的流程講清楚了,實際專案中改用標準 API 會更簡短也更好維護。