How Would I Calculate Sums And Averages Of Printed Numbers?
By Anonymous, January 23, 2015
Currently I have code that prompts the user for numbers and then displays the numbers they entered in a text box under the button for the prompt. What I would like to do is get the sum and average of all the numbers entered. Preferably this would be a number below the numbers that updates everytime a new one is entered but I could do with it being a button that does it whenever pressed. I'm also curious as to if it can even be done with the form I have it in now or if I would need an array for the prompted numbers. Here is the code:
<html>
<title>Number Seperation</title>
<body>
<p>Please enter as many numbers in the prompt box as you wish.</p>
<form>
<script>
function getInput(){
var valid = false, error = '', numb = '';
while(!valid) {
numb = prompt('Please enter numbers in the box below' + error, numb);
valid = numb.match(/\D/) == null;
error = '\n\nOnly numbers are allowed';
}
var textBox = document.getElementById('text-box');
textBox.innerHTML += 'Number entered: ' + numb + '<br>';
}
</script>
<input type="button" onclick="getInput()" value="Supply number" />
<div id="text-box"></div>
</form>
</body>