ItemPriceItem 1<...">

Input Calculation

I have several tables that look like this:

<table id="table1">
<tr>
    <th>Item</th>
    <th>Price</th>
</tr>
<tr>
    <td>Item 1</a></td>
    <td><input type="text" name="sum1" id="sum1" /></td>
</tr>
<tr>
    <td>Item 2</a></td>
    <td><input type="text" name="sum2" id="sum2" /></td>
</tr>
<tr>
    <td>Item 3</td>
    <td><input type="text" name="sum3" id="sum3" /></td>
</tr>
<tr>
    <td>&nbsp;</td>
    <td>Total:</td>
    <td>$total </td>
</tr>
</table>



<table id="table2">
<tr>
    <th>Item</th>
    <th>Price</th>
</tr>
<tr>
    <td>Item 1</a></td>
    <td><input type="text" name="sum1" id="sum1" /></td>
</tr>
<tr>
    <td>Item 2</a></td>
    <td><input type="text" name="sum2" id="sum2" /></td>
</tr>
<tr>
    <td>Item 3</td>
    <td><input type="text" name="sum3" id="sum3" /></td>
</tr>
<tr>
    <td>Item 4</td>
    <td><input type="text" name="sum4" id="sum4" /></td>
</tr>
<tr>
    <td>&nbsp;</td>
    <td>Total:</td>
    <td>$total</td>
</tr>
</table>

Does anyone know if it is possible to summarize the prices of the goods for each entry (separately for table1, table2, etc.). And in the end, print the sum of the items from all the items?

+3
source share
3 answers

You will need a dom manipulator like jQuery or just javascript. I would give the fields a class to make it even easier - say, "sum." Then you can capture all the "sums" of children from parent tables. Divide their value by int and add. Not so bad.

Here is an example JS working script

+1
source

jquery, , "" - "total" , ,

function calculateSum(tableId){
 var sum = 0;
 $(tableId + ' .line-item').each(function(){
   var value = parseFloat($(this).val().trim());
   if(value){
    sum += parseFloat($(this).val());
   }
 });
 $(tableId + ' .total').html(sum);
}

, .

, tuffer , .line-item input, . .total tr:last-child td:nth-child(2)

UPDATE: "parseInt",

0

, . - , .

:

  • .
  • table <input> s ( , );
  • Calculate the total amount for all inputs for the current table.

You can do this using JavaScript, but jQuery is best for you.

BUT: do not call HTML DOM elements with similar identifiers. It is not right!!!

0
source

All Articles