實務上的核取框群組通常要滿足兩個條件:點全選時底下全部勾上、再點一次全部取消;而只要有一個子項被勾選,全選框就該亮起來,全部取消則全選框也熄燈。
/**
* 全選函式
* @param mainId 主要核取框的 id
* @param klass 下屬核取框共用的 class
*/
function selectAll(mainId, klass){
$("." + klass).each(function(){
if($("#" + mainId).attr("checked") == "checked"){
$(this).attr("checked", "checked");
}else{
$(this).removeAttr("checked");
}
});
}
這段完成的是全選與全不選;至於要送出哪些 id,在控制器端接收核取框陣列即可。
/**
* 子核取框有一個選中,父核取框就選中
* 子核取框全不選,父核取框不選中
* @param father 父核取框的 id
* @param son 子核取框的 class
*/
function checkSonCheckBox(father, son){
$("." + son).click(function(){
if($(this).attr("checked") == "checked"){
$(this).addClass("checked");
}else{
$(this).removeClass("checked");
}
if($("." + son).hasClass("checked")){
$("#" + father).attr("checked", "checked");
}else{
$("#" + father).removeAttr("checked");
}
});
}
這裡用 checked 這個 class 當作「曾經被勾選」的標記,再靠 hasClass() 判斷整體狀態。
上述寫法有個關鍵問題:jQuery 1.6 之後,核取框的勾選狀態必須用 prop() 操作,attr("checked") 回傳的是 HTML 初始屬性,做不出可靠的狀態判斷;removeAttr("checked") 在部分版本上也不會真正取消勾選。改寫如下:
function selectAll(mainId, klass){
var checked = $("#" + mainId).prop("checked");
$("." + klass).prop("checked", checked);
}
function checkSonCheckBox(father, son){
$("." + son).click(function(){
var $sons = $("." + son);
var $checked = $sons.filter(":checked");
$("#" + father).prop("checked", $sons.length === $checked.length);
// 若要做出「部分勾選」的半選狀態
$("#" + father).prop("indeterminate", $checked.length > 0 && $checked.length < $sons.length);
});
}
改寫後少了 checked class 的迂迴,也不必逐一走訪——直接比較「總數」與「已勾選數」就能一次判斷三種狀態。加上 indeterminate 之後,部分勾選時全選框會顯示為一條橫線,使用者一眼就看懂。
記得在文件就緒後呼叫初始化:$(function(){ checkSonCheckBox('allSelect', 'son'); });