ScudBud ScudBud - 6 months ago 17
HTML Question

Real time update subtotal in order form

I'm trying to set up an order form, and I want to show the subtotal right next to the item, and I want it to update real time as they change it. I tried building a javascript to make this work, but couldn't figure it out.



<table>
<tr>
<td width="48"><strong>PRICE</strong></td>
<td width="144"><strong>QTY</strong></td>
<td width="84"><div align="center"><strong>SUBTOTAL</strong></div></td>
</tr>
<tr>
<td>$7.00</td>
<td><input name="Item1" type="number" id="Item1" max="5" min="0" value="0"></td>
<td><div align="center"><span id="span_totalItem1">$0.00</span></div></td>
</tr>
<tr>
<td>$9.54</td>
<td><input name="Item2" type="number" id="Item2" max="5" min="0" value="0"></td>
<td><div align="center"><span id="span_totalItem2">$0.00</span></div></td>
</tr>
</table>




Answer
<script type="text/javascript">
function updateItem1() {
    var x = document.getElementById("Item1").value;
    document.getElementById("span_totalItem1").innerHTML = "$" + x*7;
}

function updateItem2() {
    var x = document.getElementById("Item2").value;
    document.getElementById("span_totalItem2").innerHTML = "$" + x*9.54;
}
</script>

And add the event oninput on your two inputs:

<table>
  <tr>
    <td width="48"><strong>PRICE</strong></td>
    <td width="144"><strong>QTY</strong></td>
    <td width="84"><div align="center"><strong>SUBTOTAL</strong></div></td>
  </tr>
  <tr>
    <td>$7.00</td>
    <td><input name="Item1" type="number" id="Item1" max="5" min="0" value="0" oninput="updateItem1()"></td>
    <td><div align="center"><span id="span_totalItem1">$0.00</span></div></td>
  </tr>
  <tr>
    <td>$9.54</td>
    <td><input name="Item2" type="number" id="Item2" max="5" min="0" value="0" oninput="updateItem2()"></td>
    <td><div align="center"><span id="span_totalItem2">$0.00</span></div></td>
  </tr>
</table>