2010-10-14 91 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

相關問題