-3

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.

zzgooloo
  • 75
  • 3
  • 9

2 Answers2

1

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)');
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
1

On Cancel null is returned

 var a = prompt("ask user something", "")
    if (a === null) {
      alert(' Cancel pressed')
    }

JSFIDDLE

brk
  • 48,835
  • 10
  • 56
  • 78