0

Basically, I'm trying to create a quiz app (well, not really a quiz, basically clicking one option leads to another question set exactly for that option.) And don't mind the stupid questions and answers I've put in there - those are placeholders.

The error that I've gotten is that the pos variable seems to reset everytime I call renderQuestions().

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>yo</title>
    <style>
        #test {
            background-color: red;
        }
    </style>
</head>
<body>
    <div id="test"></div>

    <script>
        var pos = 0;
        var questions = [
            ["What the fish?", "fish", "gun", "fcuk", "duck", "muck"],
            ["You selected fish", "damn"],
            ["You selected gun", "gun"]
        ]
        function _(x) {
            return document.getElementById(x);
        }
        function renderQuestions() {
            test = _("test");
            console.log(pos);
            question = questions[pos][0];
            test.innerHTML += question + "<br>";
            for(var i = 0; i < questions[pos].length - 1; i++) {
                test.innerHTML += "<input type='radio' name='choices' value='"+i+"'>" + questions[pos][i+1] + "<br>";
            }
            test.innerHTML += "<button onclick='processAnswer("+pos+")'>Submit</button>";
        }
        function processAnswer(pos) {
            if(pos == 0) {
                choices = document.getElementsByName("choices");
                for(var i = 0; i < choices.length; i++) {
                    if(choices[i].checked) {
                        choice = choices[i].value;
                    }
                }
                if(choice == "0") {
                    pos = 1;
                    console.log(pos);
                } else if(choice == "1") {
                    pos = 2;
                } else {
                    alert("No position set")
                }
                renderQuestions();
            } else {
                alert("Out of bounds")
            }
        }
        renderQuestions();
    </script>
</body>
</html>

Here is what it looks like when I debug it in the console: console

It seems like after clicking the radio button, it succesfully sets the pos to 1, but then immediately resets it to 0. Why is that?

  • `function processAnswer(pos)` - `pos` is not what you expect it to be inside the fundtion. Remove `pos` as the function's parameter – baao Mar 06 '18 at 13:51
  • Deleting the pos parameter fixed it! Thanks for the comment! :D –  Mar 06 '18 at 14:07

1 Answers1

5

If you want pos to act like a global variable, don't pass it to your processAnswer() function, don't have an argument pos in that function.

It's a matter of variable scope. You're currently only modifying a local copy of pos that won't change the value of pos in your renderQuestions() function.

kshetline
  • 12,547
  • 4
  • 37
  • 73