Live javascript calculating

Hi there!

I hope one of you javascript experts can help me out on this one. In html and PHP I made a purchase script. Al the products are listed inside a WHILE loop. The problem is, when I POST it starts entering data in the database. I would like the possibility that when I enter a number in the “aantal” field that it instantly calculates live how much it is going to cost.

So, “aantal$i” * inkoop_prijs = Subtotal
And, all Subtotals together = Total

Big respect to the one that solves this


[COLOR="Red"]	<?php 
		if(isset($leverancier_id)) { 
		$i = 1;
		$totaal = 0;
	
			while($prodinfo = mysql_fetch_assoc($prodres)) {  ?>[/COLOR]
	<tr>	
		<td>[COLOR="red"]<?=$prodinfo['product_id'];?>[/COLOR]</td>
		<td>[COLOR="red"]<?=$prodinfo['naam'];?>[/COLOR]</td>
		<td align="center"><input name="aantal[COLOR="red"]<?=$i;?>[/COLOR]" type="text" value="[COLOR="red"]<?=$_POST['aantal'.$i];?>[/COLOR]" size="5" /></td>
		<td>[COLOR="red"]<?=number_format($prodinfo['inkoop_prijs'], 2);?>[/COLOR]</td>	
		<td align="right">
		<input type="hidden" name="product_id<[COLOR="red"]?=$i;?>[/COLOR]" value="[COLOR="red"]<?=$prodinfo['product_id'];?>[/COLOR]" />
		<input type="hidden" name="inkoop_prijs[COLOR="red"]<?=$i;?>[/COLOR]" value="[COLOR="red"]<?=$prodinfo['inkoop_prijs'];?>[/COLOR]" />[COLOR="Blue"]Subtotal[/COLOR]</td>
	</tr>
[COLOR="Red"]	<?php 
	$i++;
	} }
	?>[/COLOR]

	<tr>
		<td colspan="2" valign="top" align="right"><strong>[COLOR="Blue"]Total:[/COLOR]</strong></td>
		<td colspan="2" valign="top">incl. 19&#37; BTW </td>
		<td align="right"><strong>&euro; </strong></td>
	</tr>

var aantals = document.getElementById('product_info').getElementsByTagName('input'), total = document.getElementById('total'), prijs, subtotal;
for (var i = 0, j = aantals.length; i < j; i++) {
  if (aantals[i].name.indexOf('aantal') === 0) {
    prijs = aantals[i].parentNode.nextSibling.nextSibling.firstChild.value;
    subtotal = prijs * aantals[i].value;
  }
  else if (aantals[i].name.indexOf('inkoop_prijs') === 0) {
    aantals[i].value = subtotal;
    total.firstChild.nodeValue = parseInt(total.firstChild.nodeValue, 10) + subtotal;
  }

You’ll need to change the <strong>Total:</strong> to:

<strong>Total: <span id="total"></span></strong>

And the table that contains all this stuff will need to have an ID of product_info (or change the ID above).

I suspect you should not be using a table for this as it doesn’t really seem like tabular data. Are you working with a CMS from the 1990s?