user3453690
user3453690

Reputation: 13

Setting a variable within an if statement - JQuery

I'm trying to set a variable within an if statement but for some reason it isn't working! I'm really bad with JQuery/Javascript, so I was hoping someone could help. Here's the code I'm working with:

if($("#myicon").hasClass('opacity0')) {
var variable = 1;
}

Any ideas? Thanks!

EDIT: I should add that I'm trying to use this along with charts.js to make a doughnut chart. So, for example

var doughnutData = [
        {
            value: variable,
            color:"#000000"
        }
    ];

If I manually say "value: 1," it works. But when I try to set it using a variable it doesn't create a chart.

Upvotes: 1

Views: 6768

Answers (2)

Nguyen Tran
Nguyen Tran

Reputation: 1188

The variable within the if statement just is used for itself(local variable).

You should declare this variable above the if statement.

var variable;

if($("#myicon").hasClass('opacity0')) {
    variable = 1;
}

var doughnutData = [
    {
        value: variable,
        color:"#000000"
    }
];

Hope it helpful!

Cheers.

Upvotes: 1

andrew
andrew

Reputation: 9583

If you're trying to access variable elsewhere in you code then just drop the var so that you're not declaring it on the local scope.

Global variables are not the ideal way to code but without seeing the rest of your code I can't suggest much more

Upvotes: 1

Related Questions