fiterpilot fiterpilot - 4 months ago 8
Javascript Question

Why wont my text update? (HTML + JS)

I am trying to make text on my site update. The variable in JS does, but the text on screen doesn't. (Yes I know the code is sloppy, I get it to work and then go through and make it pretty.)

<script>
var moneyTotal = 370; //Variable for money, filled with starter money
var moneyText = String(moneyTotal); //Variable for text
var OD2Clicked = 0;
</script>
<script>document.write("<h1 class='money'>Total: $"+ moneyText + "</h1>"); //Line for updating site </script>

<script>
function Check(){ //Function that checks for radio button change
if (document.getElementById('OD2').checked & OD2Clicked==0) {
OD2Clicked = 1;
Adding(20);
console.log("Adding");
}else if(document.getElementById('OD').checked & OD2Clicked>0){
OD2Clicked = 0;
Adding(-20);
console.log("Subtracting");
}

setTimeout(function() {Check()}, 5000);
}


function Adding(m1){ //Function for adding
moneyTotal += m1;
moneyText = String(moneyTotal);
console.log(moneyTotal);
console.log(moneyText+" Text");
}
</script>

Answer

Just like I mentioned above in the comment:

Your screen write happens only once when Browser will parse all tags. You need to update your text on the screen every time you modify the value.

Would this work for you?

<script>
    var moneyTotal = 370; //Variable for money, filled with starter money
    var OD2Clicked = false;

    var timeoutPeriod = 5000;
</script>
    <script>document.write("<h1 class='money'>Total: $0</h1>"); //Line for updating site </script>

<script>
    function Check(){ //Function that checks for radio button change
        if (document.getElementById('OD2').checked) {
            if (!OD2Clicked) {
                OD2Clicked = true;
                moneyTotal += 20;
                console.log('Adding');
            } else if (OD2Clicked) {
                OD2Clicked = false;
                moneyTotal -= 20;
                console.log('Subtracting');
            }

            // Find DOM element we need to update
            document
                .querySelectorAll('.money')[0]
                .textContent = 'Total: $' + moneyTotal;
        }

        setTimeout(Check, timeoutPeriod);
    }
</script>