0


I have the flowing code:

 QuestionID = 0;
 var score1 = 0;
 var score2 = 0;

 function clickanswer(answer) { 
    QuestionID++;
    if (QuestionID <= 50) {
        if (QuestionID == 2 || QuestionID == 5) {
            score1 = score1 + answer;}
        if (QuestionID == 4 || QuestionID == 7) {
            score2 = score2 + answer; }
    }
}
function useScores(){
   var data1 = score1;
   var data2 = score2; }

The clickanswer(answer) is an onlick event function from a button.
How can I use score1 and score2 variables from clickanswer(answer) function in useScores() function? Thanks.

6
  • first call click answer(call from useScores() ), then you can use score1 and score2 varibales Commented Jun 18, 2014 at 12:13
  • 4
    since you defined score1 and score2 on top of both function you can use them in both functions. Commented Jun 18, 2014 at 12:13
  • score1 and score2 are global variables, so they can be used in all functions. Commented Jun 18, 2014 at 12:14
  • Are you sure you want to increment QuestionID before deciding how the scores should compute? Looks buggy to me. Commented Jun 18, 2014 at 12:16
  • Pass them as parameters. Commented Jun 18, 2014 at 12:17

1 Answer 1

1

Not 100% sure what you mean. But I think it's one of these 2.

  1. Just call the useScores() function at the bottom of your clickanswer() function. As score1 and score2 are both global variables, they will both be usable in the function. E.g.

    function clickanswer(answer) { 
        QuestionID++;
        if (QuestionID <= 50) {
            if (QuestionID == 2 || QuestionID == 5) {
                score1 = score1 + answer;}
            if (QuestionID == 4 || QuestionID == 7) {
                score2 = score2 + answer; }
        }
        useScores();
    }
    
  2. Or else, you're wanting to pass the variables into the useScores() function. In which case, something like this might be what you want.

    function clickanswer(answer) { 
        QuestionID++;
        if (QuestionID <= 50) {
            if (QuestionID == 2 || QuestionID == 5) {
                score1 = score1 + answer;}
            if (QuestionID == 4 || QuestionID == 7) {
                score2 = score2 + answer; }
        }
        useScores(score1, score2);
    }
    
    function useScores(score_1, score_2){
        var data1 = score_1;
        var data2 = score_2;
    }
    
Sign up to request clarification or add additional context in comments.

1 Comment

thanks Andrew, solution 2 was what I needed, it is simple but now I know how to do it.

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.