View Full Version : Get the number of edited inputs

Rain Lover
03-05-2019, 01:31 PM

Every semester my students need to take at least one test. The following form gives the right average grade of a student:

<!DOCTYPE html>
<html lang="en">
<title>Average Grade</title>
Math: <input type="number" id="test1">
<input type="number" id="test2">
<input type="number" id="test3">
<output id="average"></output>
<input type="button" value="Calculate" id="calcBtn">
document.getElementById('calcBtn').addEventListener('click', function() {
var test1 = document.getElementById('test1').value;
var test2 = document.getElementById('test2').value;
var test3 = document.getElementById('test3').value;
var average = document.getElementById('average');
average.value = (Number(test1)+Number(test2)+Number(test3)) / 3;
DEMO (https://jsfiddle.net/Mori/p2m0tvfy/4/)

The problem is it works right only if all the fields are edited. If the student doesn't take some tests, the average grade won't show the right value. I know it's because of dividing by the fixed number 3 when it calculates the average grade:

average.value = (Number(test1)+Number(test2)+Number(test3)) / 3;


What is a simple approach to get the number of changed input fields?

03-06-2019, 08:37 AM
One possible solution...