jQuery sum checkbox values

前端 未结 2 834
迷失自我
迷失自我 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/

    0 讨论(0)
  • 2020-12-22 13:24

    You can use .not() to exclude #total element value from calculations, .get() , Array.prototype.reduce() , + operator to cast value of :checkbox to Number

    $(":checkbox").change(function(event) {
      $("#total").val(function() {
        return $(event.target.tagName).not("[type=text]")
        .get().reduce(function(a, b) {
            return +a.value + +b.value
        })
      })
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
    </script>
    <input type="checkbox" id="basic_single" name="basic_single" value="400">
    <input type="checkbox" id="basic_double" name="basic_double" value="680">
    <input type="text" name="total" value="" size="30" id="total">

    0 讨论(0)
提交回复
热议问题