简体   繁体   English

如何在删除字段时计算输入字段值并将其分配给另一个字段

[英]How to calculate input fields values and assign it to another field while removing a field

I am trying to calculate the total amount of a group of repetitive fields. 我正在尝试计算一组重复字段的总数。

This is my markup 这是我的标记

<label for="name" class="p-label-required">Amount <span style="color: red"> (Numbers only)</span></label>
<input type="text" id="amount" name="amount[]" placeholder="Amount" required="required" class="form-control inputChangeVal reqF" data-js-input-type="number" /><br/>

<div class="add_another_st"></div>
<button class="btn add_another_st_btn" style="margin-bottom: 25px;">+</button>
<hr style="margin-top: 0;">
Total Amount:
<input type="text" class="totalAmount" id="updatedTotalAmount" style="font-size: 20px; font-weight: bold; margin-bottom: 25px; border: 0;" readonly />

and this is my jQuery to calculate the total whenever something happens on the amount fields.. it calculates the total correctly and assign it to the total amount field. 这是我的jQuery,用于在amount字段发生任何事情时计算总计。.它可以正确计算总计并将其分配给total amount字段。

/* calculating and updating the total amount */
    function updateTotal() {
        var price = 0;

        jQuery(".inputChangeVal").each(function() {
            var t = parseFloat(jQuery(this).val(), 10);
            price = price + t;
        });

        var total = price.toFixed(2);
        jQuery(".totalAmount").val(total);
        console.log('updateTotal Runs');
    }
    jQuery(document).on("change, keyup", ".inputChangeVal", updateTotal);

but I want to calculate the amount again when an amount field is removed and it does not work / update the total whenever and amount field is removed. 但是我想在删除金额字段时再次计算金额,并且无论何时删除金额字段都无法使用/更新总数。

the code I've created for this is here in js fiddle 我为此创建的代码在js小提琴中

How can I update the total again while a field is removed? 删除字段后,如何再次更新总数?

You need to call the updateTotal() function upon sliding up of the wrapper element. 您需要在wrapper元素向上滑动时调用updateTotal()函数。

jQuery(this).parent('div').slideUp(1000, function() {
    jQuery(this).remove();
    x--;
    updateTotal(); // updating total
});

Working fiddle 工作提琴

jQuery(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
        debugger;
        e.preventDefault();
        jQuery(this).parent('div').slideUp(1000, function() {
                jQuery(this).remove();

                x--;
        /*running again calculation 0f the total amount and while removing an amount */
        var price = 0;
        jQuery(".inputChangeVal").each(function() {
                var t = parseFloat(jQuery(this).val(), 10);
                price = price + t;
        });
        var total = price.toFixed(2);
        jQuery(".totalAmount").val(total);
        console.log('updateTotal Runs while removing');
         });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM