首页 > 解决方案 > jquery - 计算使用 checkAll 按钮选中的所有复选框

问题描述

我有一个脚本,可以将 div 中所有选中的复选框值与 class="show_list_item" 相加。它工作正常。

我还有一个脚本,允许用户一键检查所有复选框(id="checkAll")。它也运行良好。

当用户使用“checkall”按钮时,脚本不再计算选中/选中的值。

我该如何解决?

查询

// CALCULATE TOTAL CHECKED
$('input:checkbox').change(function ()
{
    var total_srvs_amount = 0;
    $('.show_list_item input[name="amount"]:checkbox:checked').each(function(){ 
        
        total_srvs_amount += isNaN($(this).val()) ? 0 : Number ($(this).val());
        
    }); 
    
    $("#total_sum").text(total_srvs_amount);
});

// CHECK ALL CHECKBOXS
$(function () {
    var chkMain = $('.checkAll input:checkbox#checkAll , .checkAll input:checkbox.checkAllBtn');
    $(chkMain).change(function () {
        $('.checkAll input:checkbox').not(this).prop('checked', this.checked);

    });

});

HTML

<div id="1" class="obj_res_box show_list_item">

    <input type="checkbox" class="" value="" id="checkAll">

    <table class="checkAll">
        <tr>
            <td><input type="checkbox" name="amount" value="138.75"></td>
            <td><input type="checkbox" name="amount" value="120"></td>
            <td><input type="checkbox" name="amount" value="64"></td>
        </tr>
    </table>
</div>

<div id="2" class="obj_res_box hide_list_item">
....
</div>

<div id="total_sum">0</div>

标签: jquery

解决方案


// CHECK ALL CHECKBOXS 函数有错误。

我已经纠正了。请查阅

// CALCULATE TOTAL CHECKED
$('input:checkbox').change(function ()
{
    var total_srvs_amount = 0;
    $('.show_list_item input[name="amount"]:checkbox:checked').each(function(){ 
        
        total_srvs_amount += isNaN($(this).val()) ? 0 : Number ($(this).val());
        
    }); 
    
    $("#total_sum").text(total_srvs_amount);
});

// CHECK ALL CHECKBOXS
$(function () {
    var chkMain = $('input:checkbox#checkAll');
    $(chkMain).change(function () {
        $('.checkAll input:checkbox').prop('checked', this.checked);
       $('.checkAll input:checkbox').trigger('change');
    });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="1" class="obj_res_box show_list_item">

    <input type="checkbox" class="" value="" id="checkAll">

    <table class="checkAll">
        <tr>
            <td><input type="checkbox" name="amount" value="138.75"></td>
            <td><input type="checkbox" name="amount" value="120"></td>
            <td><input type="checkbox" name="amount" value="64"></td>
        </tr>
    </table>
</div>

<div id="2" class="obj_res_box hide_list_item">
....
</div>

<div id="total_sum">0</div>


推荐阅读