0

Noob here. I do not know why the userInput variable is not coming out in the alertbox i am creating

<!DOCTYPE HTML>
<html>
    <head>
        <title>fns</title>
    </head>
    <body>
        <button onclick="namebox()">Enter Name</button>
        <button onclick="yoyoyo()">Generate Greeting!</button>

    </body>
    <script>
    function namebox() {
        var userInput = prompt("Enter your name");
    }
    function yoyoyo() {
        alert("Hello" + userInput);
    }
    </script>
</html>```
Josh Hales
  • 394
  • 2
  • 12
gnarm
  • 59
  • 6

1 Answers1

0

The issue you're having here is that the scope of userInput is limited to the namebox function. You'd have to raise the scope so it's accessible in both functions.

<html>
<head>
<title>fns</title>
</head>
<body>
<button onclick="namebox()">Enter Name</button>
<button onclick="yoyoyo()">Generate Greeting!</button>

</body>
<script>
var userInput; // declared outside both functions, so scope is available in both
function namebox() {
    userInput = prompt("Enter your name");
}
function yoyoyo() {
    alert("Hello" + userInput);
}
</script>
</html>
xdumaine
  • 10,096
  • 6
  • 62
  • 103