Using the prompt() Method
The prompt() method is a little different from the other two you have looked at in the course of this chapter. This is the only one that either allows the user to type in his own response to the question, instead of the script just processing information it already has (as with the alert() method), or allows the user to choose OK or Cancel (available using the confirm() method).
You add the prompt() method in much the same way as the other two. To begin with, add the prompt() method to the <script> block:
The prompt() method now starts to differ from the other two methods because two pieces of text must be added within the parentheses. The first is the message you want to appear.
This is done in exactly the same way as before. Again, the text goes inside the parentheses and inside quotes:
Save this page and view it in the browser. Notice that the prompt appears, asking the user for his name (see Figure 3.9). You can type it in and proceed by clicking OK, or you can click Cancel.
Note the word undefined in the input box. This is an Internet Explorer feature; Netscape Navigator simply leaves the box blank (see Figure 3.10).
Another piece of text we can add is the default text to appear in the actual input box of the prompt. Adding this is simple and gets rid of the ugly looking "undefined" that Internet Explorer displays. Here is what you need to do. After the first piece of text inside the parentheses, place a comma outside the quotes, and after that place a second piece of text (again in quotes). Here is an example of this in action:
Save the page again and refresh the browser. Notice how the once- empty input box now contains the text from the second set of quotes (see Figure 3.11).
Exercise - Practice adding the prompt() method to a Web page. Add your own messages and default text for the input box.
Add a couple of separate prompt() methods to a Web page and note the result.
Add some comments (single- and multi-line) to your pages explaining what happens and what each part is.