检查所有功能正在检查所有复选框而不是指定的ID

时间:2019-06-04 00:15:37

标签: jquery html

我尝试使用类名,ID以及复选框的名称,但是每次我执行checkall函数时,无论ID,名称,类如何,它都会检查页面上的所有复选框。我什至做到了这一点,以使复选框ID /类在其末尾具有一个计数器,并具有jquery函数进行计数,并使用该计数器根据当前计数来查找该复选框,但仍然导致选中所有复选框。

jquery:

        $(document).ready(function() {
            $('#check_all_batch').change(function() {
                var batch_add_checkboxes = $('input[name="batch_add[]"]').length;
                if($(this).is(":checked")) {
                    for (var autoinc = 1; autoinc <= batch_add_checkboxes; autoinc++) {
                        $("#batch_add_"+autoinc).prop('checked', $(this).prop("checked"));
                        console.log(autoinc);
                    }
                } else {
                    for (var autoinc = 1; autoinc <= batch_add_checkboxes; autoinc++) {
                        $("#batch_add_"+autoinc).prop('checked',false);
                        console.log(autoinc);
                    }
                }
            });
        });

html:

<!-- at the top of the form, outside of foreach loop -->
<input type="checkbox" id="check_all_batch"> 
<!-- two checkboxes inside of foreach -->
<input type="checkbox" name="reimbursement[]" value="1"> // this is the one that keeps checking itself as well as the below checkboxes when this has nothing in common with the below checkbox
<input type="checkbox" id="batch_add_'.$expenses_count.'" name="batch_add[]" value="1">

在当前情况下,基于结果,我有一个PHP foreach循环,其计数器从1开始,然后上升到13

带有日志输出的浏览器控制台显示正确的数字:

1
2
3
4
5
6
7
8
9
10
11
12
13

任何帮助都会很棒。我肯定这是我忽略的东西。

1 个答案:

答案 0 :(得分:0)

我认为您可以用更简单的方式做到这一点:

$('#check_all_batch').on( 'change', function() {
    $( 'input[type="checkbox"][name="batch_add[]"]').prop("checked", $(this).prop( 'checked'));

});