Total and Average Input Numbers

[Total: 0    Average: 0/5]

This will tally up text box input and show the total and average.

Body Code:

<form name=f1>
Box 1<input onblur=addTotals(1) type=text name=item1 value=4>
<BR>
Box 2<input onblur=addTotals(1) type=text name=item2 value=7>
<BR>
Total (1 and 2):
<input type=text name=total_1 value="?" readonly>
<BR>Average (1 and 2):
<input type=text name=avg_1 value="?" readonly>
<HR>
Box 3<input onblur=addTotals(2) type=text name=item3 value=4>
<BR>
Box 4<input onblur=addTotals(2) type=text name=item4 value=7>
<BR>
Total (3 and 4):
<input type=text name=total_2 value="?" readonly>
<BR>Average (3 and 4):
<input type=text name=avg_2 value="?" readonly>
</form>
<script language="javascript"> 
function addTotals(_v) { 
  with (document.forms["f1"])
  {
    var totalResult=0;
    if(_v==1)
	{
      totalResult = Number( item1.value ) + Number( item2.value ); 
      avg_1.value = roundTo( totalResult / 2, 2 );
      total_1.value = roundTo( totalResult, 2 );
	}
    if(_v==2)
	{
      totalResult = Number( item3.value ) + Number( item4.value ); 
      avg_2.value = roundTo( totalResult / 2, 2 );
      total_2.value = roundTo( totalResult, 2 );
	}
  }
} 


function roundTo(num,pow){ 
  if( isNaN( num ) )
  { 
    num = 0; 
  } 

  num *= Math.pow(10,pow); 
  num = (Math.round(num)/Math.pow(10,pow))+ "" ; 
  if(num.indexOf(".") == -1) 
    num += "." ; 
  while(num.length - num.indexOf(".") - 1 < pow) 
    num += "0" ; 

  return num; 
} 



</script>

Times Viewed: 0

Leave a Reply

Your email address will not be published. Required fields are marked *