按行选中和取消选中复选框

Check and uncheck the checkbox by row

大家好...我有多个行是通过 foreach 循环从我的数据库中获取的。

我每行有 2 个复选框,我正在尝试的是...如果我选中第一个复选框,则意味着自动需要选中第二个复选框。

为此,我将 ID 用于 select 第二个复选框,现在由于该 ID 对于每一行都是相同的,如果我 select 第一行,第一个复选框意味着它 selecting 所有第二个复选框。但我需要的是让特定的 selected 行的第二个复选框需要被选中。 任何人帮助。很抱歉没有分享像 jsfiddle 这样的现场演示。我希望你们能理解我的问题。

<thead>
<th><input type="checkbox" id="select_all"></th>
</thead>

<?php foreach ($category_details as $key => $category_detail): ?>
<tr>
<td>

  <input type="checkbox" class="checkbox" id="select_img" name="ids[]" value="<?php echo $category_detail['id'];?>"/>
  <input type="checkbox" class="checkbox checkimg" name="imgs[]" value="<?php echo  $category_detail['category_image'];?>"/>

</td>

<td>...</td> <!-- etc -->
</tr>
<?php endforeach ?>

    $(document).ready(function(){
    $('#select_all').on('click',function(){
        if(this.checked){
            $('.checkbox').each(function(){
                this.checked = true;
            });
        }else{
             $('.checkbox').each(function(){
                this.checked = false;
            });
        }
    });

    $('#select_img').on('click',function(){
        if(this.checked){
            $('.checkimg').each(function(){
                this.checked = true;
            });
        }else{
             $('.checkimg').each(function(){
                this.checked = false;
            });
        }
    });

    $('.checkbox').on('click',function(){
        if($('.checkbox:checked').length == $('.checkbox').length){
            $('#select_all').prop('checked',true);
        }else{
            $('#select_all').prop('checked',false);
        }
    });
});

您可以使用兄弟jquery功能。例如:

$('.whole_row').on('click',function(){

    if(this.checked){
    
        $(this).siblings().each(function(index, checkbox){
            checkbox.checked = true;
        });
    }else{
         $(this).siblings().each(function(index, checkbox){
            checkbox.checked = false;
        });
    }
});

这样它将迭代兄弟标签并且不会超出 table 行。只需使用 类 而不是 id 编辑:

只是一个风格注释

$('.whole_row').on('click',function(){
    let check = this.checked;
    $(this).siblings().each(function(index, checkbox){
        checkbox.checked = check;
    });
});

html 像这样:

<tr>
    <input type="checkbox" class="whole_row">one
    <input type="checkbox">two
    <input type="checkbox">three
    <input type="checkbox">four
</tr>