Search code examples
javascriptpromptconfirm

JavaScript Cancel on Prompt


Hi I was wondering what the difference between the prompt() method and confirm() methods are?

and also: I was wondering how to modify the following code, so that when the user cancels the prompt box, a block of code is executed.

var userInput = prompt("Write your name","");
if(prompt == //user cancels//){
code to be executed;
}

Thanks.


Solution

  • If user cancels prompt, then it returns null.
    Since null is falsy, you can simply check for !prompt:

    var result = prompt("ask user something");
    if (!result) {
    
    };
    

    However, in your case, it looks like you want confirm function.
    The difference is that prompt is a text input dialog, which returns inputed string or null.
    Confirm is Yes / No dialog, which returns true or false.

    var result = confirm('Click Yes or No!');
    
    // Both approaches are working, choose the one you like:
    if (result) console.log('Yes (result)');
    if (result === true) console.log('Yes (result === true)');
    
    // Both approaches are working, choose the one you like:
    if (!result) console.log('No (!result)');
    if (result === false) console.log('No (result === false)');