Communicate with the use
Among the methods belonging to the window object, there are some designed specifically to help your page communicate with the user by assisting with the input and output of information.
alert()
You’ve already used the alert() method to pop up an information dialog for the user. You’ll recall that this modal dialog simply shows your message with a single OK button. The term modal means that script execution pauses, and all user interaction with the page is suspended, until the user clears the dialog. The alert() method takes a message string as its argument:
alert("This is my message"); alert() does not return a value.
confirm()
The confirm() method is similar to alert(), in that it pops up a modal dialog with a message for the user. The confirm() dialog, though, provides the user with a choice; instead of a single OK button, the user may select between OK and Cancel, as shown in snapshot. Clicking on either button clears the dialog and allows the calling script to continue, but the confirm() method returns a different value depending on which button was clicked—Boolean true in the case of OK, or false in the case of Cancel. We begin to look at JavaScript’s data types in the next section, but for the moment you just need to know that a Boolean variable can only take one of two values, true or false.
The confirm() method is called in a similar way to alert(), passing the required message as an argument:
var answer = confirm("Are you happy to continue?");
Note that here, though, we pass the returned value of true or false to a variable so we can later test its value and have our script take appropriate action depending on the result.
prompt()
The prompt() method is yet another way to open up a modal dialog. In this case, though, the dialog invites the user to enter information.
A prompt() dialog is called in just the same manner as confirm():
var answer = prompt("What is your full name?");
The prompt method also allows for an optional second argument, giving a default response in case the user clicks OK without typing anything:
var answer = prompt("What is your full name?", "John Doe");
The return value from a prompt() dialog depends on what option the user takes:
- If the user types in input and clicks OK or presses Enter, the user input string is returned.
- If the user clicks OK or presses Enter without typing anything into the prompt dialog, the method returns the default response (if any), as optionally specified in the second argument passed to prompt().
- If the user dismisses the dialog (that is, by clicking Cancel or pressing Escape), then the prompt method returns null.