jQuery sum checkbox values

前端 未结 2 833
迷失自我
迷失自我 2020-12-22 12:50

I\'d need to calculate sum of all checkboxes and update total based on selection here is html:



        
2条回答
  •  离开以前
    2020-12-22 13:18

    You need to consider only the items which are checked to calculate the total. For this, you can only target the elements which are checked and iterate through each loop to add their values to calculate the sum. Following example involves no hardcoding of individual elements.

    $('input:checkbox').change(function ()
    {
          var total = 0;
          $('input:checkbox:checked').each(function(){ // iterate through each checked element.
            total += isNaN(parseInt($(this).val())) ? 0 : parseInt($(this).val());
          });     
          $("#total").val(total);
    
    });
    

    Example : https://jsfiddle.net/8p3ftmuh/2/

提交回复
热议问题