如何用JavaScript更新兄弟姐妹复选框?

时间:2015-08-10 23:41:16

标签: javascript jquery html css checkbox

我正在尝试实现JavaScript来更新其对应div中的复选框兄弟。我有多个具有相同复选框选项的div:#check_all_checkboxes,#check_none和.others。我希望div更新他们的兄弟姐妹,但JavaScript不会更新兄弟姐妹。我可以对兄弟类或id进行硬编码,JavaScript将在第一个div上成功执行,但不会在连续的div上执行。

    // Select ALL checkboxes
    $('#check_all_checkboxes').click(function () {
        if ( $(this).is(':checked') ){
            $(this).siblings('.others').prop('checked', true);
            $(this).siblings('#check_none').removeAttr('checked');
        }
    });

    // Select NO checkbox(es)
    $('#check_none').click(function () {
        if ( $(this).is(':checked') ){
            $(this).siblings('.others').removeAttr('checked');
            $(this).siblings('#check_all_checkboxes').removeAttr('checked');
        }
    });

    // Select other checkbox(es)
    $('.others').click(function () {
        $(this).siblings('#check_none').removeAttr('checked');
        $(this).siblings('#check_all_checkboxes').removeAttr('checked');
    });

2 个答案:

答案 0 :(得分:1)

这篇文章表明你可能会更好地使用.prop('已检查',false): .prop('checked',false) or .removeAttr('checked')?

答案 1 :(得分:0)

根据charlietfl的建议使用唯一ID而不重复ID。我能够使用类来完成这项工作。

// Select ALL checkboxes
$('.check_all_checkboxes').click(function () {
  if ( $(this).is(':checked') ){
    $(this).siblings('.others').prop('checked', true);
    $(this).siblings('.check_none').removeAttr('checked');
  }
});

// Select NO checkbox(es)
$('.check_none').click(function () {
  if ( $(this).is(':checked') ){
    $(this).siblings('.others').removeAttr('checked');
    $(this).siblings('.check_all_checkboxes').removeAttr('checked');
  }
});

// Select other checkbox(es)
$('.others').click(function () {
  $(this).siblings('.check_none').removeAttr('checked');
  $(this).siblings('.check_all_checkboxes').removeAttr('checked');
});
<div id="1">
    Div ID 1<br>
    <input type="checkbox" class="check_all_checkboxes">Select All<br>
    <input type="checkbox" class="check_none">Select None<br>
    <input type="checkbox" class="others">Select other1<br>
    <input type="checkbox" class="others">Select other2<br>
    <input type="checkbox" class="others">Select other3<br>   
</div>        

<hr>        
        
<div id="2">
    Div ID 2<br>
    <input type="checkbox" class="check_all_checkboxes">Select All<br>
    <input type="checkbox" class="check_none">Select None<br>
    <input type="checkbox" class="others">Select other1<br>
    <input type="checkbox" class="others">Select other2<br>
    <input type="checkbox" class="others">Select other3<br>   
</div>