I'm creating an online calculator to get the average grade of different tests my students take and also the final grade. I wonder if you see any problems in this update or any way to improve it:
var inputs = document.getElementsByTagName('input'); var i; 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++; } } if (!count) { return 'Please enter a grade.'; } return 'Average: ' + (total / count).toFixed(1); } document.getElementById('calculator').addEventListener('click', function() { var physicsTests = document.getElementById('physics').getElementsByTagName('input'); var physicsAverage = document.getElementById('physicsAverage'); physicsAverage.value = calculateAverage(physicsTests); var historyTests = document.getElementById('history').getElementsByTagName('input'); var historyAverage = document.getElementById('historyAverage'); historyAverage.value = calculateAverage(historyTests); var finalGrade = document.getElementById('finalGrade'); var averagesTotal = physicsAverage.value.slice(9) * 3 + historyAverage.value.slice(9) * 2; if (averagesTotal || averagesTotal == 0) { finalGrade.value = 'Final grade:' + (averagesTotal / 5).toFixed(1); } else { finalGrade.value = ''; } }); document.getElementById('resetter').addEventListener('click', function() { var form = document.getElementById('form'); var edited = calculateAverage(inputs); if (edited != 'Please enter a grade.' && confirm('Your changes will be lost.\nAre you sure you want to reset?')) { form.reset(); } }); window.addEventListener('beforeunload', function(event) { var edited = calculateAverage(inputs); if (edited != 'Please enter a grade.') { event.returnValue = 'Your changes may be lost.'; } }); <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> P.S. I've made changes to the previous code to shorten the script and added some new features such as a reset button.
Note
Please review the final product made thanks to the hints I've received in this thread.