【问题标题】:Uncheck all other checkboxes取消选中所有其他复选框
【发布时间】:2010-10-14 17:42:26
【问题描述】:

当用户单击复选框时,我需要清除所有其他复选框。与单选按钮的行为几乎相同。用户单击复选框“A”,复选框“B”和“C”均未选中。我正在使用 jquery,但我不知道如何做到这一点。有什么想法吗?

以下是复选框的设置方式:

    <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>

【问题讨论】:

  • 为什么不使用单选按钮?这是一个简单的方法。
  • @klox - 也许 OP 想要对设计进行检查 (☑) ;)
  • 是的,我知道单选按钮会很理想,但它们不能在应用程序中使用。
  • 为什么会被否决?我的意思是它是一个奇怪的用例(除非它像“非上述”或其他东西......但仍然如此),但从文本来看,他似乎意识到他在某种程度上复制单选框行为的事实.
  • 使用兄弟姐妹解决问题;单选按钮行为。但是当您选中/取消选中 B 和 C(其他复选框)时的行为是什么

标签: javascript jquery html css


【解决方案1】:

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

$(':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>

其中,&lt;input&gt;s 和 &lt;label&gt;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

【讨论】:

  • 愚蠢的问题:什么是兄弟姐妹?我用谷歌搜索无济于事。
  • 啊,我明白了——在没有兄弟姐妹的情况下有没有办法做到这一点?
  • 我将 HTML 设置添加到我的 OP 中
  • 我又添加了一个crazy demo rrrr... ;)
【解决方案2】:
$("#checkboxA").click(function() {
    var checkedStatus = this.checked;
    $("#checkboxB_And_C_Selector").each(function() {
        this.checked = !checkedStatus;
    });
});

【讨论】:

  • 这不会完全按预期工作,因为当您单击取消选中任何框时,它会导致所有其他框都被选中。
猜你喜欢
  • 2013-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-29
  • 1970-01-01
  • 1970-01-01
  • 2016-01-29
  • 2017-01-03
相关资源
最近更新 更多