# Calculating price and total price in a table with Javascript

• Apr 16, 2007, 21:46
vediam
Calculating price and total price in a table with Javascript
I have a table with too many rows like this:

HTML Code:

```<tr> <td><?php echo \$productName; ?></td> <td><input type="text" name="UnitPrice[]" value="<?php echo \$productPrice;>" readonly="true"></td> <td><input type="text" name="Quantity[]" value="0" onChange="doCalculation();"></td> <td><input type="text" name="Price[]" value="0" readonly="true"></td> </tr> ... ... <p> Total Price : <input type="text" name="TotalPrice" value="0" readonly="true"></p>```
User can fill Quantity column.

I want to calculate "Total Price" and "Item Price (unitPrice x Price)" in the doCalculation() function when user change "Quantity" columnn of table.

How can I do this ?
• Apr 17, 2007, 07:33
vediam
Hi All,

I solved my problem. The working copy of my solution is showed below.

Sample usage on onChange event of each Quantity[] input:
CalculateColumns('Table1', 'UnitPrice[]', 'Quantity[]', 'Price[]', 'TotalPrice')

Code:

```<script language="javascript"> function CalculateColumns(ContainerID, Col1, Col2, Col3, GrandTotalID) {         if( typeof ContainerID == 'string' ) var ContainerID = document.getElementById( ContainerID );         var arrCol1 = new Array();         var arrCol2 = new Array();         var arrCol3 = new Array();         var GrandTotal = 0;         var ContainerIDElements = new Array( 'input');         //var ContainerIDElements = new Array('input', 'textarea', 'select');         for( var i = 0; i < ContainerIDElements.length; i++ ){                 els = ContainerID.getElementsByTagName( ContainerIDElements[i] );                 for( var j = 0; j < els.length; j++ ){                         if(els[j].name == Col1) arrCol1.push(els[j]);                         if(els[j].name == Col2) arrCol2.push(els[j]);                         if(els[j].name == Col3) arrCol3.push(els[j]);                 }         }         for( var j = 0; j < arrCol1.length; j++ ) {                 arrCol3[j].value = Number(arrCol1[j].value) * Number(arrCol2[j].value);                 GrandTotal += Number(arrCol3[j].value);         }                 document.getElementById(GrandTotalID).value = GrandTotal; } // CalculateColumns </script>```