Search code examples
javascriptdom-eventsjavascript-objects

Adding value to current value through prompt


I'm making simulation of a coffee machine in Javascript and have to make method which adds water to the machine. There are some conditions that had to be examined and I did that, but what I'm having problem is to add new value that is imported through prompt to current value.

Here is what I have:

addWater: function() {
    this.water = 0;

    let addWater = prompt('Unesite kolicinu vode koju zelite da dodate');

    if (addWater === null || addWater.trim().length === 0) {
        alert('Morate uneti koliko vode zelite');
        return;
    } else if (isNaN(addWater) || addWater.startsWith('-')) {
        alert('Unos mora biti pozitivna brojcana vrednost');
        return;
    } else if (addWater > 400) {
        alert('Maksimalan unos vode je 400');
        return;
    } else {
        addWater = Number(addWater);
        this.water += addWater;
    }

    this.waterStatus();
},

With this it only enters value current value, it does not add numbers, because one of the conditions is to have not more that 400 of water.

What I'm doing wrong?


Solution

  • At the top function body, there is a statement this.water = 0; . So every time the function is called the value will always be filled with a new value, not added. your code should like this

    addWater: function () { 
        let addWater = prompt('Unesite kolicinu vode koju zelite da dodate');
    
        if (addWater === null || addWater.trim().length === 0) {
            alert('Morate uneti koliko vode zelite');
            return;
        } else if (isNaN(addWater) || addWater.startsWith('-')) {
            alert('Unos mora biti pozitivna brojcana vrednost');
            return;
        } else if (addWater > 400) {
            alert('Maksimalan unos vode je 400');
            return;
        } else {
            addWater = Number(addWater);
            this.water += addWater;
        }
    
        this.waterStatus();
    }