Skip to content
Advertisement

Calculate the SUM of Fields in a dynamically changing form

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

JavaScript

ProductRecipeController.php

JavaScript

Image

How I would like it to work Image

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()

JavaScript

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:

JavaScript

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

Advertisement

Answer

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”):

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement