Hi,
I’m very new to Javascript and I’ve been trying to complete a ‘simple’ assignment for a few weeks now. Just wondering if anyone can help explain to me what is wrong with my code:
<html>
<head>
<title>Aggregates</title>
<script type=“text/javascript”>
var numbers = new Array();
function insert(input)
{
var newNumber = input.value;
input.value = "";
numbers[numbers.length] = newNumber;
}
function show()
{
var string="";
for(i = 0; i < numbers.length; i++)
string = string + numbers[i]+"\
";
document.getElementById(“e”).value = string;
}
function sum()
{
if (numbers.length == 0) return 0;
for (var i=0,total=0; i < numbers.length; i++)
total += numbers[i];
document.getElementById("Sum").value = m;
return total;
}
function mean()
{
var m = numbers.length == 0 ? 0 : sum(null)/numbers.length;
document.getElementById("Mean").value = m;
return m;
}
function resetNumbers()
{
numbers = new Array();
}
</script>
</head>
<body>
<h1>Aggregates</h1>
<h3>Add as many numbers as you like </br> to the list, then click Calculate.</h3>
<form id=“formtext” form name=“formtext”>
<input type=“text” name=“name” value=“”></input>
<input type=“button” value=“Add to list” onClick=“insert(document.formtext.name);show();”></input></br>
<textarea name="txt" id="e" rows="10" ></textarea> </br>
<input type="button" value="Calculate" onClick="sum();mean()"></input>
<input type="button" value="Reset" onClick="resetNumbers();form.reset()"></input>
<h4>Total (Sum):</h4>
<input type="text" id="Sum" value="0"></input></br>
<h4>Average:</h4>
<input type="text" id="Mean" value="0"></input></br>
</form>
</body>
</html>
On opening it in IE is tells me ‘m’ is undefined, in function sum() and function mean(). I got most of the code from a previous thread http://www.sitepoint.com/forums/showthread.php?746348-sum-mean from someone else doing the same assignment and someone posted the answer…which doesn’t work. I have been googling and found a few different ways of finding the sum and average of an array, but each way I’ve tried is not working. I tried merging the two functions together into function sumAverage:
function SumAverage()
{
var count
var Sum = 0
var Average
var result
// Find the lowest & highest
for (var i = 0; i < scores.length; i++)
Sum=Sum + scores[i]
Average = Sum/scores.length
but struggle how to correctly assignment the answer to the correct place using ‘document.getElementById’.
Any help much appreciated, it’s driving me crazy
Simon