Gandoe Dyck
Gandoe Dyck

Reputation: 97

Logical error in javascript changing classNames

This script contains logical error, where? It does only calculate avg. for first number, not second and so on...

window.onload = function() {
    var amountOfNumbers = 0;
    var total = 0;
    document.getElementById("uitkomst").innerHTML = "Er zijn nog geen cijfers ingevoerd";
    document.getElementById("cijfer").onblur = function() { 
        total = parseFloat(this.value);
        amountOfNumbers++;
        this.value = "";        
        document.getElementById("uitkomst").innerHTML = "Het gemiddelde van deze "+amountOfNumbers+" cijfers is "+(total/amountOfNumbers);
    }
};

Upvotes: 0

Views: 32

Answers (1)

Mike Cluck
Mike Cluck

Reputation: 32511

You need to increment total rather than reset it.

total += parseFloat(this.value);
//    ^--- Add to the total

Without the + there, total will be equal to the current value, not the sum of all of the numbers.

Upvotes: 3

Related Questions