Search code examples
javascripthtmlcssalertprompt

alert box not printing my user input variable from promp


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>```

Solution

  • 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>