javascriptconfirm

some problems with the final result this function in js


                var confirmation = confirm("Are you sure you want to enter your name?");
                
                function confirmTrue() {
                    var nameInput = prompt("Great! Now enter your name:");
                    return nameInput;
                }
                
                if (confirmation == true) {
                    confirmTrue();
                } else {
                    alert("I was hoping for a response..");
                }
                
                if (confirmTrue != null || confirmTrue != "") {
                    alert("Hello, " + window.nameInput);
                }
            }
            
            confirmCallName();

i want to make a function where you confirm something to type your name in, and then after the input, it will greet you with the input result. but when the prompt returns true or false, there is a final alert that says "Hello, undefined". how do I make it's so that it doesnt activate when we cancel the prompt and after I confirm the input?

someone told me that the variable is inside the function. if so, how do I make it global?


Solution

  • I made a couple of modifications to get this working how I think you want it. The code is below. You need to assign the value of the confirmTrue result to a variable and then test that. Also, you need to add the case to handle cancelling that result.

    var confirmation = confirm("Are you sure you want to enter your name?");
                    
                    function confirmTrue() {
                        var nameInput = prompt("Great! Now enter your name:");
                        return nameInput;
                    }
                    
                    if (confirmation == true) {
                        var getInput = confirmTrue();
                        if (getInput) {
                            alert("Hello, " + getInput);
                        } else {
                            alert("You cancelled your input.");
                        }
                    } else {
                        alert("I was hoping for a response..");
                    }