2010-01-27 152 views
1

我有一個CheckBoxList,其中一個選項是'All'。如果用戶選中「全部」,並且用戶未選中「全部」,我想要選擇所有選項,包括全部,我想清除選擇。如果他們選擇除「全部」之外的其他選項,則不執行任何操作。 任何人都可以幫我用jQuery來做到這一點?我使用jQuery 1.2.6CheckBoxList選擇jQuery中的所有選項

<table border="0" onclick="SelectMe(this);" id="one"> 
<tbody> 
    <tr> 
     <td> 
      <input type="checkbox" checked="checked" name="one$0" id="one_0"/><label for="one_0">All</label> 
     </td> 
     <td> 
      <input type="checkbox" name="two$1" id="two_1"/><label for="two_1">Option One</label> 
     </td> 
     <td> 
      <input type="checkbox" name="three$2" id="three_2"/><label for="three_2">Option Two</label> 
     </td> 
     <td> 
      <input type="checkbox" name="four$3" id="four_3"/><label for="four_3">Option Three</label> 
     </td> 
     <td> 
      <input type="checkbox" name="five$4" id="five_4"/><label for="five_4">Option Four</label> 
     </td> 
    </tr> 
</tbody> 

謝謝大家的幫忙。這裏是我的答案 -

綁定此功能onclick屬性爲每個checkboxlist.items的

function selectAll(box) { 

//check if this is 'All' checkbox 

var isAll = ($(box).next('label').text() == 'All'); 

//get the checkboxlist 

var theList = $(box).parents('table:first'); 

    //if 'All' is checked/clicked, check all options 

    if (isAll) { 
    var check = theList.find('input:checkbox')[0].checked; 
    $.each(theList.find('input:checkbox'), function(i, v) { 
     v.checked = check; 
    }); 
    } 

// check 'All' option if all other checkboxes are checked  
else { 
    var allchecked = true; 
    $.each(theList.find('input:checkbox'), function(i, v) { 
     if(i) if (!v.checked) allchecked = false; 
    }); 
    theList.find('input:checkbox')[0].checked = allchecked; 
} 

回答

2

以下應該工作[更新]

$(':checkbox').click(function() { 
    // check if the label following the checkbox is 'All' 
    if ($(this).next('label').text() == 'All') 
    { 
    if ($(this).is(':checked')) 
     $(':checkbox').attr('checked', true) 
    else 
     $(':checkbox').attr('checked', false); 
    } 
}); 

而更多的是正確的,而不是檢查下一個標籤,我們應根據for屬性檢查與點擊複選框相對應的標籤。

所以

if ($(this).next('label').text() == 'All') 

可能是

if ($('label[for="'+$(this).attr('id')+'"]').text() == 'All') 
+0

謝謝。但這是一個動態複選框列表,因此我不可能知道「全部」選項的ID。如上所示,我只能將jquery綁定到整個複選框列表。是否有可能找到哪個選項被選中或未選中?也就是說,檢測用戶是否選中了綁定到整個列表的jquery的「All」選項? – Dave 2010-01-27 01:53:03

+0

@Dave,檢查上面的變化,使其通用 – 2010-01-27 02:11:57

0

$(文件)。就緒(函數(){

$('input[type=checkbox]').click(function(){  //detects a check box click 
     if ($(this).attr('id').indexOf("one_0") > -1){ //Checks if 'all' check box was clicked 
      checkUncheckAll($(this).attr('checked')); //Function call to check uncheck based on checked/unchecked state of All check box 
     } 
    }); 
}); 

//Function to check uncheck all check boxes 
function checkUncheckAll(checkedValue) { 
    $('input[type=checkbox]').each(function() {   
     this.checked = checkedValue; 
    }); 
} 

這種方法有一個缺陷 - 功能checkUncheckAll遍歷所有檢查在你的表格中選中並選中/取消選中它們。如果您適當地指定其ID(即,checkSpec1,checkSpec2等)並檢測其ID爲checkSpec字的複選框,您可以爲特定的複選框設置。

我希望這會有所幫助。

歡呼聲