2011-09-19 69 views
1

我有一個表格,其值是用PHP動態生成的。表中的每一行都有一個複選框。在表格中是一個標題列,它有一個「全部接受」按鈕。如何使用JQuery切換所有Checboxes

當用戶點擊「全部接受」按鈕時,所有選擇框都被選中。但是,我想添加一個類似切換的功能:如果沒有選中框,然後按下按鈕選擇全部;如果所有框都被選中,則按下該按鈕將取消全部選擇。

下面是選擇我的所有jQuery代碼:

//Approves all 
$('#approve_all_questions').click(function() { 
    $("INPUT[type='checkbox']").attr('checked', true); 
}); 

我無法得到它的正確切換。我試過這個:

//Toggle 
$('#approve_all_questions').click(function() { 

    if($("INPUT[type='checkbox']").attr('checked', true)) 
    { 
     $("INPUT[type='checkbox']").attr('checked', false); 
    } 
    else 
    { 
     $("INPUT[type='checkbox']").attr('checked', true); 
    } 
    }); 

但是這並不奏效。

TIA。

回答

2

$("INPUT[type='checkbox']").attr('checked', true)checked屬性設置爲true,並返回一個jQuery對象,它總是計算爲true

也許你想

$("input[type='checkbox']").prop('checked', function(i, val) { 
    return !val; 
}); 

它反轉每個複選框checked值。

如果您要選擇或取消選擇所有一次,你可以這樣做:

var $boxes = $("input[type='checkbox']"), 
    $unselected = $boxes.not(function(){ 
     return this.checked; 
    }); 

// if there are any unselected boxes, it selects all, else it deselects all 
$boxes.prop('checked', $unselected.length > 0); 
0

下面是另一個代碼塊,用於演示工作:http://jsbin.com/agomuc/edit
請注意使用.live(),如果你想使用.click()你必須把你的處理程序進入

$(document).ready(function(){
// handler here
});

0

我更喜歡我的解決方案:

$(".selectAllCheckBox").live("click", function() { 
    $("input[type='checkbox']").each(function() { 
     if($(this).attr('checked')){ 
      $(this).attr('checked', false); 
     } else { 
      $(this).attr('checked', true); 
     } 
    }); 
}); 

;)