PDA

View Full Version : Get the number of edited inputs

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

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">
<head>
<title>Average Grade</title>
</head>
<body>
<form>
Math: <input type="number" id="test1">
<input type="number" id="test2">
<input type="number" id="test3">
<output id="average"></output>
<br>
<input type="button" value="Calculate" id="calcBtn">
</form>
<script>
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;
});
</script>
</body>
</html>
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;

Question

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

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

https://jsfiddle.net/0r6bhaq2/