DIV CSS 佈局教程網

JavaScript 實作 checkbox 的全選、反選與取值
編輯:關於JavaScript     

做專案時經常會遇到需要處理 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 效果。

幾個可以改進的地方

  • 用 filter 取代自製的 in_array。Array.prototype.indexOf(ES5 起標準支援)與 Array.prototype.includes(ES2016)已經能勝任這件事,不必擴充原生原型。擴充 prototype 有污染全域的風險,團隊協作時容易衝突。
  • find_str 有 bug。它用 join("") 把陣列串成字串再 indexOf,當元素為 "1" 與 "11" 時會誤判——搜尋 "1" 會找到 "11" 的位置。改用 indexOf 直接比對元素才是正確做法。
  • attr 用錯了。jQuery 1.6 之後,checked 這類狀態屬性應該用 prop() 而非 attr(),否則在部分版本中會出現狀態不同步的問題。
  • 可以更簡潔。收集勾選值其實一行就夠了:var ids = $("[name='checkboxes']:checked").map(function(){ return this.value; }).get();
  • 記得同步全選框狀態。使用者手動逐項勾選到全部選中時,上方全選框應該要跟著被勾上,這需要額外監聽每個子項的變更事件。

這份範例的價值在於把「收集 → 判斷 → 增刪」的流程講清楚了,實際專案中改用標準 API 會更簡短也更好維護。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved