简体   繁体   中英

JQuery - sum check boxes values according parent class

I have script that sum all checked checkboxs, but I would like to sum only checkboxs values where parent div has class="show_list_item"

 $('input:checkbox').change(function (){ var total_srvs_amount = 0; $('input[name="amount"]:checkbox:checked').each(function(){ total_srvs_amount += isNaN($(this).val()) ? 0 : parseInt ($(this).val()); console.log(total_srvs_amount); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="show_list_item"> <input type="checkbox" name="amount" value="100"> <input type="checkbox" name="amount" value="120"> </div> <div class="hide_list_item"> <input type="checkbox" name="amount" value="85"> <input type="checkbox" name="amount" value="90"> </div>

You can change the selector to apply the function on checkboxes inside .show_list_item :

 $('.show_list_item 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 : parseInt ($(this).val()); console.log(total_srvs_amount); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="show_list_item"> <input type="checkbox" name="amount" value="100"> <input type="checkbox" name="amount" value="120"> </div> <div class="hide_list_item"> <input type="checkbox" name="amount" value="85"> <input type="checkbox" name="amount" value="90"> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM