PDA

View Full Version : JavaScript to calculate averages



johnnyi
06-17-2005, 02:22 PM
Hi all,

I have four textboxes that will be prefilled with values when the user opens the page and I'm trying to write a script to calculate the average of these textboxes - result to appear in another textbox. For example:

Text Box 1: 10
Text Box 2: 15
Text Box 3: 25
Text Box 4: 30

Text Box 5: 20 (trying to have this box calculate the average of boxes 1-4)

I searched google and only found one that touched on this, but couldn't get it to work in this environment. Does anyone have anything that they have used in the past?

Much appreciated.

- i

jscheuer1
06-18-2005, 05:14 AM
<html>
<head>
<title>Average Boxes - Demo</title>
<style type="text/css">
input{
width:4em;
display:block
}
</style>
<script type="text/javascript">
function averageBoxes(){
var avg=(Math.abs(document.boxes.textBox1.value)+Math.abs(document.boxes.textBox2.value)+Math.abs(document.boxes.textBox3.value)+Math.abs(document.boxes.textBox4.va lue))/4
if (avg!==avg)
alert('Numbers Only Please!')
document.boxes.textBox5.value=avg
}
</script>
</head>
<body onload="averageBoxes()">
<form name="boxes">
Value 1:<input name="textBox1" value=15 onkeyup="averageBoxes()" type="text">
Value 2:<input name="textBox2" value=10 onkeyup="averageBoxes()" type="text">
Value 3:<input name="textBox3" value=25 onkeyup="averageBoxes()" type="text">
Value 4:<input name="textBox4" value=20 onkeyup="averageBoxes()" type="text">
Avg Val:<input name="textBox5" readonly type="text">
</body>
</html>If, as you say, the boxes are prefilled when the page loads and you don't want the user to be able to change the values at that point, you could make all the boxes readonly and get rid of the onkeyup events.

johnnyi
06-21-2005, 01:11 PM
Thanks jscheuer1...

Shortly after posting, I was able to create a Javascript that did this - though probably not as efficiently as your script.

I appreciate your reply.

- I