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 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动