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

Posted

技术标签:

【中文标题】逐行选中和取消选中复选框【英文标题】:Check and uncheck the checkbox by row 【发布时间】:2021-03-31 13:48:48 【问题描述】:

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

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

为此,我使用 ID 来选择第二个复选框,现在因为该 id 对于每一行都是相同的,如果我选择 第一行,第一个复选框表示它正在选择所有第二个复选框。但我需要的是让特定选定行的第二个复选框需要被选中。 任何人帮助。很抱歉没有分享任何像 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);
        
    );
);

【问题讨论】:

id 是个坏主意,id 在文档中应该是唯一的,id 选择器总是会返回第一个匹配的 id 如果您使用 jquery 和 html 代码至少使用几行输入元素创建一个 sn-p,我会为您提供帮助 哦,你能分享你的意见代码,这将解决我在 jsfiddle 中的问题 好的,我会创建 检查一下,当某些复选框未选中时,添加了全选逻辑...jsfiddle.net/user1701/62Lv9r4q 【参考方案1】:

您可以使用兄弟 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;
        );
    
);

这样它将迭代兄弟标签并且不会超出表格行。只使用类而不是 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>

【讨论】:

以上是关于逐行选中和取消选中复选框的主要内容,如果未能解决你的问题,请参考以下文章

如何通过使用alpine js单击一个复选框来选中和取消选中所有复选框

复选框 - 使用 jQuery 和 MySQL 选中或取消选中

js怎么控制多个复选框的选中和取消选中

选中/取消选中同位素中的输入复选框

如何使用 jQuery 使用按钮选中/取消选中所有复选框?

js 设置多个复选框选中和取消选中