douguwo2275 2014-08-26 01:22
浏览 52
已采纳

以动态变化的形式计算字段的总和

I am currently trying to calculate the total sum of a dynamically changing form. What I currently have is a Symfony2 collection of forms, in which I Multiply a product amount by a unitcost = ProductCost. This works great so far. Now I need to add all the ProductCost's of a form and enter the resulting figure into another field (recipecost).

I think what I need is a Foreach loop, but don't know where to start.

Calc.js

$(document).on('change', '.products, .amounts, .unit', function(event) {
var amount = $(this).parent().parent().find('.amounts').val();
var productId = $(this).parent().parent().find('.products').val();
var unit = $(this).parent().parent().find('.unit').val();
var productCostField = $(this).parent().parent().find('.product-costs');
var recipeCost = $(this).parent().parent().find('.recipecost');


console.log("Amount: " + amount + " - ProductID: " + productId + " - unit: " + unit);
if (amount == "" || productId == "" || unit == "") {
    // Don't make the Ajax call if missing one of the values
    return false;
}

// triggered every time an input field is changed
$.post(
        Routing.generate('calculate_cost'),
        {
            amount: amount,
            unit: unit,
            product: productId
        },
function(data) {
    data = JSON.parse(data);
    if (!data.success) {
        // An error was thrown in the controller
        alert(data.message);
    }
    else {
        // Update the corresponding productCost field using the data from the controller
        console.log("Product cost: " + data.productCost);
        productCostField.val(data.productCost);


var arr = document.getElementsByClassName('product-costs');
var tot=0;
for(var i=0;i<arr.length;i++){
    if(parseInt(arr[i].value))
        tot += parseInt(arr[i].value);
}
recipecostField.value = tot;
  }
 }
);
});

ProductRecipeController.php

public function getProductCostAction(Request $request) {

    $amount = $request->request->get('amount', null);
    $productId = $request->request->get('product', null);
    $unit = $request->request->get('unit', null);
    if (empty($amount) || empty($productId)) {
        return new \Symfony\Component\HttpFoundation\Response(json_encode(array('success' => false, 'message' => 'Bad input')));
    }

    $em = $this->getDoctrine()->getManager();

    $product = $em->getRepository('BCInventoryBundle:Product')->find($productId);
    $u = $em->getRepository('BCInventoryBundle:Measures')->find($unit);

    $mass = new Mass($amount, $u->getUnit());
    $fam = $mass->toUnit('g');

    if (empty($product)) {
        return new \Symfony\Component\HttpFoundation\Response(json_encode(array('success' => false, 'message' => 'Invalid product')));
    }
    $productCost = $product->getCostunit() * $fam;
    return new \Symfony\Component\HttpFoundation\Response(json_encode(array('success' => true, 'productCost' => $productCost)));
}

Image

How I would like it to work Image http://i61.tinypic.com/2rx8jll.png

To be honest I have no idea where to begin with this, I've spent the last few hours trying to figure out if I should be doing it with PHP or with Ajax, I currently have a similar function which run's as the Submit button is pressed in the end. Which looks like this:

Recipe.php/fixRecipeCost()

public function fixRecipecost() {
    $this->recipecost = 0;
    foreach ($this->product AS $pc) {
    $this->recipecost += $pc->getProductcost();
    $this->setRecipecost($this->recipecost);
    }
}

Any help much appreciated. I need to be clear that the amount of ProductCost fields could be 1 or 3000 so simply specifying each field by hand isn't an option.

Edit

I have just being trying appending this to the end of my JS:

var arr = document.getElementsByClassName('product-costs');
var tot=0;
for(var i=0;i<arr.length;i++){
    if(parseInt(arr[i].value))
        tot += parseInt(arr[i].value);
}
recipecostField.value = tot;
    }

}

But is having no effect. No error's in my log either though.

  • 写回答

1条回答 默认 最新

  • duanlu5055 2014-08-31 00:56
    关注

    I agree with user26409021, you could calculate the sum every time the AJAX call returns. Something like this should work (assuming your "Cost for Recipe" field has the id set to "recipe-cost"):

    $(document).on('change', '.products, .amounts, .unit', function(event) {
        updateProductCost(this);
    });
    
    function updateProductCost(field) {
        var amount = $(field).parent().parent().find('.amounts').val();
        var productId = $(field).parent().parent().find('.products').val();
        var unit = $(field).parent().parent().find('.unit').val();
        var productCostField = $(field).parent().parent().find('.product-costs');
        var recipeCost = $(field).parent().parent().find('.recipecost');
    
        console.log("Amount: " + amount + " - ProductID: " + productId + " - unit: " + unit);
        if (amount == "" || productId == "" || unit == "") {
            // Don't make the Ajax call if missing one of the values
            return false;
        }
    
        // triggered every time an input field is changed
        $.post(
                Routing.generate('calculate_cost'),
                {
                    amount: amount,
                    unit: unit,
                    product: productId
                },
        function(data) {
            data = JSON.parse(data);
            if (!data.success) {
                // An error was thrown in the controller
                alert(data.message);
            }
            else {
                // Update the corresponding productCost field using the data from the controller
                console.log("Product cost: " + data.productCost);
                productCostField.val(data.productCost);
                calculateRecipeCost();
            }
        });
    }
    
    function calculateRecipeCost() {
        var totalCost = 0;
        $('.product-costs').each(function(index, value) {
            if ($.isNumeric($(this).val())) {
                totalCost = totalCost + parseFloat($(this).val());
            }
        });
        $('#recipe-cost').val(totalCost);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求指导ADS低噪放设计
  • ¥15 CARSIM前车变道设置
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存