Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change global variable value with a local variable

I'm trying to change a global variable by setting it as a parameter in a function. The problem I'm running into is that my global variable does not change when I change the local variable. I understand that the scope of the variables is what's causing this, but I do not know how to make it work. Here is the code I'm using:

    var blnUpgradeGlobal;

    function SelectUpgrade(strUpgradeName, blnUpgradeLocal) {
        if (blnUpgradeLocal) {
            blnUpgradeLocal= false;
            $("#" + strUpgradeName).css("background-color", "#EAC300")
        }
        else {
            blnUpgradeLocal= true;
            $("#" + strUpgradeName).css("background-color", "Lime")
        }
    }

<div id="Upgrade1" onclick="SelectUpgrade(this.id, blnUpgradeGlobal)">
Content
</div>  

So What I'm trying to accomplish here is so that when the user clicks the div, it toggles the boolean global variable set in the onClick event. I don't want to specify the exact variable in the function because I would then need to write a big nested if statement because there are a bunch of upgrades.

Thank you in advance.

like image 923
Vandel212 Avatar asked Dec 17 '25 15:12

Vandel212


2 Answers

There are 2 possible options:

  1. Change the 2nd parameter name (from blnUpgradeLocal to something else) in the function declaration

  2. Change the global variable value using window.blnUpgradeGlobal reference

The former is better

like image 123
zerkms Avatar answered Dec 19 '25 05:12

zerkms


a global var can be accessed and changed anywhere in the code.
Get rid of the parameter and then use it.
What is happening is that you are passing in the value of the global but only changing the value of the local var because the local namespace is searched first

like image 32
aaronman Avatar answered Dec 19 '25 04:12

aaronman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!