开发者

How do I sum sub-totals fields to calculate grand total?

I have a form for the item, quantity, price fields which user dynamically adds or deletes. Now I want to add sub totals and the grand totals to the form.

Until now, I have been able to use the following code, but this just subtotals for the first row and not for the rest of the rows, and also grand total is also required.

Javascript:

function totalprice()
{
    a = document.form1.quantity.value
    b = document.form1.price.value

    c = a * b

    document.form1.total.value = c
} 

HTML:

<form action="here.php" method="post" name="form1">
    Quantity: <input name="quantity" size="10">Price: <input name="price" size="10" onblur="totalprice();"><br>
    Total: <input name="total" size="10" readonly=true开发者_如何学编程><br>
    <input type="submit" value="Submit">
</form>


Assuming you have no other forms:

function SetTotals()
{

// Overall total.
var total = 0;

//  Get all forms for individual items.
var formArray = document.getElementsByTagName("form");

//  Loop all forms setting the total foreach item and incrementing the total value.
for (var i in formArray)
{
var form = formArray[i];

// Set value total value for this form.
form.total.value = form.quantity.value * form.price.value;

// Increment total for all forms.
total += form.total.value;
}

// All forms looped that total obtained, set it on the total value element.
document.getElementById("<The total element id>").value = total;
}

As usual with my answers I haven't tested it but the principle is correct. If you have other types of forms in the document then a single if check for the correct type of form should be done (perhaps it should be done anyway).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜