1

I can't seem to get either variable report1 or report2 to have a global scope, I know this problem seems really basic, but I just can't seem to find an answer.

I have to define the variable report1 when numClicks == 1, and then report2 when numClicks == 2. But JavaScript is forgetting the variables as soon as numClicks changes, which is understandable. However, I just cannot seem to widen the scope of the variables. I know for PHP you can do something like return $variable to make it global, but nothing is really working here in JavaScript.

              <?
                "<img  height =\"16\"  src = \"images/stapler.png\"  
                onclick=\"

                    numClicks++;
                if(numClicks == 1){
                    var report1 = '".$reports[$i]."';
                }
                if(numClicks == 2){
                    var report2 = '".$reports[$i]."';
                }
                return confirm(report1);

                \">\n";?>

When the script is executed, on the third click it is returning undefined.

3 Answers 3

3

Whenever you use the var syntax, you are redeclaring the variable.

You need to define the var report1; var report2; outside of your functions in the global scope; within your function, just do a plain assignment (i.e. report2 = ...;)

Sign up to request clarification or add additional context in comments.

2 Comments

Doh! I knew it must be simple
Actually, you don't need to declare the variable at all, just use it!
1

Using "var" will make the variable local to the scope. By eliminating that keyword, it will be global.

(Overly simplified, but that's the basic trick.)

Comments

1

To give a global scope to a variable, just omit the "var" keyword:

 report1 = '".$reports[$i]."';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.