Ƥŕaśađ Şŕįɱał Ƥŕaśađ Şŕįɱał - 4 months ago 13
Javascript Question

Run JavaScript at the beginning

I have a JS function to calculate given data multiply by another input data.

var item1unitp = 150;
var item2unitp = 320;

function total () {

var x1 = document.getElementById('t1').value;
var x1p = parseInt(x1);
var tot1 = item1unitp * x1p;

var x2 = document.getElementById('t2').value;
var x2p = parseInt(x2);
var tot2 = item2unitp * x2p;

var tot = tot1+tot2;

document.getElementById('tot').innerHTML = tot;
}


and my HTML

Item 1 : <input type="text" id="t1" value="1" onkeyup="total();"/> <br/><br/>

Item 2 : <input type="text" id="t2" value="1" onkeyup="total();"/> <br/><br/>

Sub Total : <span id="tot"></span>


This code is working but at the beginning of the page this span is showing nothing. But I already added value 1 to each input. How I get an initial subtotal at the beginning???

Answer

i think this is what u are expecting please tell me if it is wrong.

Sub Total : <span id="tot" value="total()"></span>
<script>
var item1unitp = 150;
var item2unitp = 320;

function total() {

  var x1 = document.getElementById('t1').value;
  var x1p = parseInt(x1);
  var tot1 = item1unitp * x1p;
  var x2 = document.getElementById('t2').value;
  var x2p = parseInt(x2);
  var tot2 = item2unitp * x2p;
  var tot = tot1+tot2;

  document.getElementById('tot').innerHTML = tot;
  return tot;
}
total();
</script>