Home > Blockchain >  JavaScript Variables adds themselves and stacks up
JavaScript Variables adds themselves and stacks up

Time:10-03

So when I want to calculate variable1 variable2 * variable3 it only add themselves and stacks up.
Code:

function randomRange(min, max) {
    return Math.floor(Math.random() * (max - min   1))   min;
}

function func() {
    var pxL = localStorage["pxL"];
    var val = document.getElementById("bp").innerHTML;
    document.getElementById("bp").innerHTML = funcCalc(val, randomRange(1, 10), pxL);
}
function funcCalc(val, random, px) {
    return val   random * px;
}

The thing is that in HTML document there is element which indicates the variable, and the variable would add itself random and multiply by third variable on button click. The problem is that the variables calculate themselves and instead of changing the innerHTML, they adds it to innerHTML.
HTML:

<stat id="bpT">BPT: <textarea class="statIndic" id="bp" disabled>0</textarea></stat>

I want output like 15 and not 015 etc.

CodePudding user response:

You need to get an integer, not a string:

    var pxL = parseFloat(localStorage["pxL"]);
    var val = parseFloat(document.getElementById("bp").innerHTML);
    document.getElementById("bp").innerHTML = funcCalc(val, randomRange(1, 10), pxL);

.innerHTML returns a string for sure. Depending on how you store the variable, localStorage might return a string or number.


You can also use Number():

    var pxL = Number(localStorage["pxL"]);
    var val = Number(document.getElementById("bp").innerHTML);
  • Related