Main updates
• Added a new function to detect changes to the input fields.
function detectChanges() { var inputs = document.getElementsByTagName('input'); for (i = 0; i < inputs.length; i++) { if (inputs[i].value) { return true; } } } Final code
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); } function detectChanges() { var inputs = document.getElementsByTagName('input'); for (i = 0; i < inputs.length; i++) { if (inputs[i].value) { return true; } } } 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 (isNaN(averagesTotal)) { finalGrade.value = ''; } else { finalGrade.value = 'Final grade:' + (averagesTotal / 5).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.'; } }); input { width: 5em; } <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>