2010-10-14 63 views
8

当用户单击复选框时,我需要清除所有其他复选框。几乎和单选按钮一样。用户点击复选框'A',复选框'B'和'C'都未选中。我正在使用jquery,但我无法弄清楚如何做到这一点。有任何想法吗?取消选中所有其他复选框

这里是如何的复选框,设置U:

<div class="sales_block_one"> 
<span class="sales_box_option_set"><input type="checkbox" value="1" id="exopt10i11553501716" name="optset[0][id]" /><label for="exopt10i11553501716">Test + &pound;100.00</label></span> 
<span class="sales_box_option_set"><input type="checkbox" value="2" id="exopt11i21553501716" name="optset[1][id]" /><label for="exopt11i21553501716">Test + &pound; 200.00</label></span> 
<span class="sales_box_option_set"><input type="checkbox" value="3" id="exopt12i31553501716" name="optset[2][id]" /><label for="exopt12i31553501716">Test 3 + &pound;400.00</label></span> 
</div> 
+2

为什么你不使用单选按钮?这是一个简单的方法。 – klox 2010-10-14 09:09:45

+1

@klox - 也许OP想要在设计上检查(☑); – Reigel 2010-10-14 09:12:03

+0

是的,我知道单选按钮是理想的,但它们不能在应用程序中使用。 – Thomas 2010-10-14 09:12:18

回答

17

如果所有的复选框是兄弟,这只是这样,

$(':checkbox').change(function(){ 

    if (this.checked) { 
     $(this).siblings(':checkbox').attr('checked',false); 
    } 

}); 

crazy demo

好吧,如果你真的想复制单选按钮的行为,这样简单,

$(':checkbox').change(function(){ 
     this.checked = true; 
     $(this).siblings(':checkbox').attr('checked',false);  
}); 

crazy demo

兄弟姐妹是当元件具有一个相同的父/容器。

样品

<div> 

<input type="checkbox" /><label>A</label> 
<input type="checkbox" /><label>B</label> 
<input type="checkbox" /><label>C</label> 
<input type="checkbox" />​<label>D</label> 

</div> 
在于

<input> S和<label> s为兄弟姐妹。


在你的情况下,它不是兄弟姐妹,你能做到这样,

$('.sales_block_one :checkbox').change(function() { 
    var $self = this; // save the current object - checkbox that was clicked. 
    $self.checked = true; // make the clicked checkbox checked no matter what. 
    $($self).closest('span') // find the closest parent span... 
     .siblings('span.sales_box_option_set') // get the siblings of the span 
     .find(':checkbox').attr('checked',false); // then find the checbox inside each span and then uncheck it. 
});​ 

crazy demo

more about traversing

+1

+1多数民众赞成在使用“兄弟姐妹”更好的方式 – klox 2010-10-14 09:07:47

+0

愚蠢的问题:什么是兄弟姐妹?我谷歌搜索无济于事。 – Thomas 2010-10-14 09:17:28

+0

请参阅编辑请... – Reigel 2010-10-14 09:22:48

1
$("#checkboxA").click(function() { 
    var checkedStatus = this.checked; 
    $("#checkboxB_And_C_Selector").each(function() { 
     this.checked = !checkedStatus; 
    }); 
}); 
+0

这不会像预期的那样正常工作,因为它会导致所有其他盒子在您检查时点击取消选中任何一个框。 – 2013-12-09 19:35:32

相关问题