2010-01-27 153 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字的复选框,您可以为特定的复选框设置。

我希望这会有所帮助。

欢呼声