Search code examples
javascriptmultiplication

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;
    }
}


Solution

  • 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;
    }