Main updates
------------
- Added a new function to detect changes to the input fields. It's used when resetting the form or reloading the page.
- Used two separate functions to calculate and display averages.
- Removed the `slice` method.
<br>
Final code
----------
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var i;
function detectChanges() {
var inputs = document.querySelectorAll('input');
for (i = 0; i < inputs.length; i++) {
if (inputs[i].value) {
return true;
}
}
}
function calculateAverage(tests) {
var total = 0;
var count = 0;
for (i = 0; i < tests.length; i++) {
if (tests[i].value) {
total += Number(tests[i].value);
count++;
}
}
return total / count;
}
function displayAverage(tests) {
var avg = calculateAverage(tests);
if (isNaN(avg)) {
return 'Please enter a grade.';
} else {
return 'Average: ' + avg.toFixed(1);
}
}
document.getElementById('calculator').addEventListener('click', function() {
var physicsTests = document.querySelectorAll('#physics > input');
var physicsAverage = document.getElementById('physicsAverage');
physicsAverage.value = displayAverage(physicsTests);
var historyTests = document.querySelectorAll('#history > input');
var historyAverage = document.getElementById('historyAverage');
historyAverage.value = displayAverage(historyTests);
var finalGrade = document.getElementById('finalGrade');
var averagesTotal = (calculateAverage(physicsTests) * 3 + calculateAverage(historyTests) * 2) / 5;
// course average * its weight; weights total = 5
if (isNaN(averagesTotal)) {
finalGrade.value = '';
} else {
finalGrade.value = 'Final grade: ' + averagesTotal.toFixed(1);
}
});
document.getElementById('resetter').addEventListener('click', function() {
var form = document.getElementById('form');
if (detectChanges() && confirm('Your changes will be lost.\nAre you sure you want to reset?')) {
form.reset();
}
});
window.addEventListener('beforeunload', function(event) {
if (detectChanges()) {
event.returnValue = 'Your changes may be lost.';
}
});
<!-- language: lang-css -->
input {
width: 5em;
}
<!-- language: lang-html -->
<form id="form">
<p id="physics">
Physics:
<input type="number">
<input type="number">
<input type="number">
<output id="physicsAverage"></output>
</p>
<p id="history">
History:
<input type="number">
<input type="number">
<input type="number">
<output id="historyAverage"></output>
</p>
<button type="button" id="calculator">Calculate</button>
<button type="button" id="resetter">Reset</button>
<output id="finalGrade"></output>
</form>
<!-- end snippet -->