This is my first post here. I'm new to Javascript and here's my problem:
I have four input fields in html. All the four input fields are not necessary to be filled by the user; one would be enough. Now my question is how to get the average of the inputs whether the user has given me only one filled field or 2 or 3 or even four of them filled.
Here's my starting code but there's a problem with it.
function calculateAll() {
//first create an array to gather inputs from user and create the sum
var listening_avg_array = new Array();
listening_avg_array[0] = parseInt(listeningInput1_js.value);
listening_avg_array[1] = parseInt(listeningInput2_js.value);
listening_avg_array[2] = parseInt(listeningInput3_js.value);
listening_avg_array[3] = parseInt(listeningInput4_js.value);
//now we calculate the average for listening scores
var sum = 0;
for (var i = 0; i < listening_avg_array.length; i++) {
sum += listening_avg_array[i];
}
var avg = sum / listening_avg_array.length;
listening_avg_span_js.innerHTML = avg;
}
Unfortunately I get a "NaN" error if the user has given me only 3 or less inputs; But if the user gives me all the four inputs the code works, but it's only one of the possible conditions. Sometimes I may only get 2 fields from the user and I have to get the average by dividing the sum by 2.
I don't know how to do it.
And here's the html:
<input id="listening-input1" type="number" min="60" max="100">
<input id="listening-input2" type="number" min="60" max="100">
<input id="listening-input3" type="number" min="60" max="100">
<input id="listening-input4" type="number" min="60" max="100">