Jump to content

using two variables in another function?


galvin

Recommended Posts

I have a function that sets two variables (var rightanswerid and var rightanswertext).  At the end of that function, another function is called this way...

 

compare(rightanswerid);	

 

Then comes the other function that does stuff with "rightanswerid" and it works fine.  But within this 2nd funtion is also this line below, but it's not working (i presume because the variable doesn't stay declared from one function to the next)...

 

document.getElementById('answer').innerHTML = rightanswertext;

 

QUESTION: What can I do to the variable rightanswertext in the first function so that it's value carries over to the next function?

 

Link to comment
Share on other sites

Your problem has to do with variable scope. A variable created/used in one function is not the same as another variable of the same name in another function - UNLESS the variables are declared as global. Different programming languages can handle variable scope differently. For JavaScript any variable declared outside of a function will be global. Variables declared inside functions are not. You can, however, pass variables into a function as needed. Whether you should use a global variable or just pass them to the needed functions depends greatly on the context.

 

I'd suggest doign a google seach for "Javascript variable scope" for more resources.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.