user6377440
user6377440

Reputation:

How to make elements appear only when button is clicked in javascript

I'm trying to get answer to display when I press the Show Button but I can't get it to work. Could someone help me understand what I am doing wrong. I can get the first part to work where I generate a random integer. But the second part does not execute (JSFiddle).

<!DOCTYPE html>
<html>

<body>
    <button class="button" onclick="disp()">Generate</button>
    <button class="button" onclick="show_ans()">Show</button>

    <script>
        function disp() {
            var i = Math.floor((Math.random() * 51) + 1);
            var j = 2 * i;
            document.getElementById("Goal").innerHTML = [i];

            function show_ans() {
                document.getElementById("answer").innerHTML = [j];
            }
        }
    </script>

    <p> Random Integer:
        <span id="Goal"></span>
    </p>

    <p> Computed Answer:
        <span id="answer"></span>
    </p>

</body>

</html>

Upvotes: 0

Views: 44

Answers (1)

David
David

Reputation: 218930

show_ans only exists within the scope of the disp function, so anything outside that scope (such as the rest of the page) can't invoke it.

Move it outside that function:

function disp() {
    //...
}
function show_ans() {
    //...
}

Of course, since show_ans also relies on j, that too will need to exist in a scope where both functions can access it:

var j;
function disp() {
    var i = Math.floor((Math.random() * 51) + 1);
    j = 2 * i;
    document.getElementById("Goal").innerHTML = [i];
}
function show_ans() {
    document.getElementById("answer").innerHTML = [j];
}

Upvotes: 1

Related Questions