0

I want to make a thing that adds two numbers with prompt()s and when it returns the sum it shows the numbers in the wrong way. For instance, I would put 5 for the first number and 2 for the second number and it returns 52. Here's the code

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<body>
    <h2 id="h2">gonna be something</h2>
    <button onclick="math()">might do something</button>
    <script>
        function math() {
        var text = document.getElementById("h2")
        var question1 = prompt("enter a number","here")
        var question2 = prompt("enter a second number","here")
        text.innerHTML = 
        question1 += question2
        }
    </script>
</body>
</html>

1 Answers1

1

You have to convert the prompt return to int in order to do the calculation. If you don't do it, the values will be concatenated instead of added.

var question1 = parseInt(prompt("enter a number","here"))
var question2 = parseInt(prompt("enter a second number","here"))

You can also test if the input was really a number before the conversion:

var question1 = prompt("enter a number","here")
var question2 = prompt("enter a second number","here")

if (!isNaN(question1) && !isNaN(question2)){
  question1 = parseInt(question1)
  question2 = parseInt(question2)
}
fonini
  • 3,243
  • 5
  • 30
  • 53