M Smith
M Smith

Reputation: 430

How can I generate 2 random numbers? Why doesn't my method work?

I'm currently trying to learn JavaScript and wanted to write a program that generates 2 random integers. My attempt was as follows

<!DOCTYPE html>
<html>
<body>
    <button onclick="myFunction()">Generate</button>

    <p id="demo"></p>

    <script>

        function myFunction() 
        {
            var x = Math.floor((Math.random() * 10) + 1);
            var y = Math.floor((Math.random() * 10) + 1);

            document.getElementById("demo").innerHTML = x ", " y;
        }

    </script>

</body>
</html>

However, this does not work. Can anyone explain what I'm doing wrong? It works when I only have x, but not when I have x and y.

Upvotes: 0

Views: 57

Answers (1)

Daniel Corzo
Daniel Corzo

Reputation: 1075

Check this out

<!DOCTYPE html>
<html>
<body>
    <button onclick="myFunction()">Generate</button>

    <p id="demo"></p>

    <script>

        function myFunction() 
        {
            var x = Math.floor((Math.random() * 10) + 1);
            var y = Math.floor((Math.random() * 10) + 1);

            document.getElementById("demo").innerHTML = x + ", " + y;
        }

    </script>

</body>
</html>

The problem was:

x ", " y

Right way:

x + ", " + y

Upvotes: 2

Related Questions