jquery sum of multiple input fields if same class in one input

前端 未结 8 1426
迷失自我
迷失自我 2020-12-14 02:49

Hello I need to sum the values of same class input in one input with class name total.




        
相关标签:
8条回答
  • 2020-12-14 03:13
    $('.qty1').each(function(){
      sum += parseFloat(this.value);
       });
    console.log(sum);
    
    0 讨论(0)
  • 2020-12-14 03:20

    I think your issue is here:

    $("#destination").val(sum);
    

    change it to:

    $(".total").val(sum);
    

    And instead of change event i suggest you to use keyup instead.

    $(document).on("keyup"
    
    0 讨论(0)
  • 2020-12-14 03:21

    I suggest this solution:

    html

    <input type="text" class="qty1" value="" />
        <input type="text" class="qty1" value="" />
        <input type="text" class="qty1" value="" />
        <input type="text" class="qty1" value="" />
        <input type="text" class="qty1" value="" />
        <input type="text" class="qty1" value="" />
    
        <input type="text" class="total" value="" />
    
    <div id="result"></div>
    

    js

    $(".qty1").on("blur", function(){
        var sum=0;
        $(".qty1").each(function(){
            if($(this).val() !== "")
              sum += parseInt($(this).val(), 10);   
        });
    
        $("#result").html(sum);
    });
    

    fiddle

    0 讨论(0)
  • 2020-12-14 03:26

    You almost had it:

    $(document).on("change", ".qty1", function() {
        var sum = 0;
        $(".qty1").each(function(){
            sum += +$(this).val();
        });
        $(".total").val(sum);
    });
    

    http://jsfiddle.net/DUKL6/1

    0 讨论(0)
  • 2020-12-14 03:26

    The problem with all of the above answers is that they fail if you enter something other than a number. If you want something that is more friendly to users, you should do some validation, perhaps even give some feedback when a value other than a number is entered.

    $('body').on('change', '.qty1', function() {
        var total=0;
        $(".qty1").each(function(){
            quantity = parseInt($(this).val());
            if (!isNaN(quantity)) {
                total += quantity;
            }
        });
        $('.total').val('Total: '+total);
    });
    
    0 讨论(0)
  • 2020-12-14 03:29

    $(document).on("keyup", ".qty1", function() {
        var sum = 0;
        $(".qty1").each(function(){
            sum += +$(this).val();
        });
        $(".total").val(sum);
    });

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