Need help creating a calculator that updates when values change
Hello fellow coders, I have a problem I need some help on. I have to make an average calculator on a website with javascript wherre the average updates when values change in the input boxes.
Here is my code so far:
Um, JavaScript goes in <script> tags, for starters. Not in <head> and not in "onchange" attribute. You can put some js in onchange, according to web browsers.. but don't.
What you want to do, is grab all of the inputs that are in the form, add them all together, and divide them by the number of boxes.. 5. Then, you want to store that result inside of the "result" input.
I suggest moving the result input outside of the form, so that you can use the form to grab all of the "box" inputs. You can simplify your html to this:
Now, with that in place, you can use JavaScript to get the average when a key is typed on any box like so:
Code:
<form id="average">
Box 1 <input type="text" value="1" /><br />
Box 2 <input type="text" value="2" /><br />
Box 3 <input type="text" value="3" /><br />
Box 4 <input type="text" value="4" /><br />
Box 5 <input type="text" value="5" />
</form>
<hr />
Result <input type="text" id="result" value="0">
<script>
(function () { // This begins our javascript code:
// Get the form
var form = document.getElementById('average');
// grab the result
var result = document.getElementById('result');
// grab the inputs, and turn them into an array:
var inputs = Array.prototype.slice.call(
// grab the input tags from inside our form:
form.getElementsByTagName('input')
);
// only run some code "once", not everytime 'average' is called:
var once = false; // We have not run the average code yet, hence 'false'.
// Create and run the 'average' function:
(function average () {
// res will be the result of 'average'.
// i and box are for dealing with the for loop and individual boxes.
var i, box, res = 0; // start 'res' at 0 for addition.
for (i in inputs) {
box = inputs[i];
if (!once) { // Have we ran this code once yet?
box.addEventListener('keyup', average);
// This will call 'average' when 'keyup' is triggerred on our box.
}
res += parseInt(box.value); // add the "int" version of the box's value to 'res'
}
// 'res' is now the sum of all the box values.
once = true; // The average code has now run at least once, hence 'true'
// Assign the average to 'result's value.
result.value = res / 5; // this divides the sum of all the boxes by 5- the number of boxes.. the average.
}()); // This ends & runs the 'average' function.
}()); // This closes our code.
</script>
Bookmarks