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

前端 未结 8 1428
迷失自我
迷失自我 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: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);
    });
    

提交回复
热议问题