javascript - 多个输入值相加或相减总计

标签 javascript jquery input

我有这段代码,但无法正常工作。

这个想法是,每个输入都有一个值,并根据您点击向上还是向下按钮从总价中求和或减去其值。

现在只是疯狂地添加、添加、添加。

非常感谢。

JS:

$( document ).ready(function() {
    $(".quantity").each(function(){
        $(this).change(function(){
            var quantity = ($(this).val());
            var ammount = ($(this).attr("data-price"));
            var price = $(this).closest(".bookSection").find(".item_price").html();
            var subtotal = ammount * quantity;
            var total = parseInt(subtotal) + parseInt(price);
            $(this).closest(".bookSection").find(".item_price").html(total);
        });
    });
});

这里是例子: http://jsbin.com/tolequyobi/1/edit?html,js,output

最佳答案

不要尝试使用.item_price,只需从一开始就计算它。如果不是,您将需要存储旧值才能知道是否需要添加或减去。

你可以做这样的事情

$('.quantity').change(function(){ // check change on the inputs
    var total = 0; // set the total to 0
    $(this).parent().find('.quantity').each(function() { // loop on all the items thats in this block
        total += parseInt($(this).attr('data-price')) * parseInt($(this).val()); // add to the total their value
    });
    $(this).parent().find(".item_price").html(total); // and then add it to your html
});

关于javascript - 多个输入值相加或相减总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41987233/

相关文章:

javascript - URI 错误 : malformed URI sequence?

javascript - 父div之外的类的Jquery最接近方法

Java 基本代码片段

html - 如何自定义html消息<输入类型=“file”>?

javascript - 在 anchor 上执行 Javascript 的最佳方式

javascript - 将 View 呈现为 JavaScript

javascript - 正确访问 <ul> 中的图像

javascript - 可点击 tr 但不能点击子项

javascript - 计数 child + 更改 CSS

c# - 如何使用InputSimulator模拟远程桌面上的特定按键?