Bich Le The
Bich Le The

Reputation: 57

By increasing a value, another value is increased by that amount

So I have this code, where I want with a button increase amount and by increasing amount the weight changes with it.

The result of the code below, by clicking the button innerText changes to for example

1piece = 8 g
2piece = 16 g
3piece = 48 g -> here is the problem - I want the number increase by the first value (3 * 8 = 24), but its doing (3 * 16)

How can I can set the weight variable to be fixed when multiplying? The weight is not a variable set on 8, but has for every element a different value, thats why its called in const. Element are from JSON file in an array map

let amount = document.getElementById('amount');
let weight = document.getElementById('weight');

function add(am, wg) {
    {
        amount = parseInt(document.getElementById(am).innerText);
        weight= parseInt(document.getElementById(wg).innerText);
        amount++
        
        let totalPt = weight * amount

        document.getElementById(am).innerText = amount;
        document.getElementById(wg).innerText = totalPt;
    }
}

Upvotes: 0

Views: 50

Answers (2)

Ankush Chavan
Ankush Chavan

Reputation: 1214

If you want the weight to be fixed to 8 while multiplying then simply set the amount to another variable and use that variable in the multiplication operation.

In the code below, I had used the fixedWeight to store the fix weight per unit. You can use this variable while multiplying.

function add(am, wg) {
    {
        amount = parseInt(document.getElementById(am).innerText);
        weight= parseInt(document.getElementById(wg).innerText);
        const fixedWeight = 8;
        amount++
    
        let totalPt = fixedWeight * amount

        document.getElementById(am).innerText = amount;
        document.getElementById(wg).innerText = totalPt;
    }
}

Upvotes: 0

Rafael Dourado D
Rafael Dourado D

Reputation: 478

You need to know the amount per weight (just do weight / amount), than you can multiply that by amount increased

function add(am, wg) {
            amount = parseInt(document.getElementById(am).innerText);
            weight = parseInt(document.getElementById(wg).innerText);
            baseweight = weight / amount;

            amount++;
            
            let totalPt = baseweight * amount;
    
            document.getElementById(am).innerText = amount;
            document.getElementById(wg).innerText = totalPt;
}

Upvotes: 1

Related Questions