Using the prompt() Method

The window prompt() method generates a dialog box that displays a scripter-defined message, a text entry field for the user, and "OK" and "Cancel" buttons.

The prompt method takes two parameters, the first being the box text which is generally used as directions, and the default text to display in the text entry field. If you don't want to include default text, it is still important to define the 2nd parameter as an empty string (""). If you don't, the default text will be, "undefined" which can be confusing to a user.
prompt("What is your name?", "")
The value returned by the prompt method will be the text string entered by the user (or empty string if the user clicked "OK" without entering text), or null if the user clicked "Cancel". Just as you can store a returned value of the confirm method in a variable, you can also store the returned value of the prompt method. Be sure to test for an empty string and null when scripting its value.

The example used here asks a user for a password to access a page. The password is then used as the page name in a statement assigning it as part of a location.href string:
function passWord(){

var pageName = prompt("Enter the password", "")

   if(pageName != "" && pageName != null){ //if user entered text and pressed OK

   location.href = pageName + ".html"


   else {

   alert("You must enter a password in order to enter the next lesson.")


function passWord()

If the user clicks "Cancel" or clicks "OK" without entering text, they remain on this page. If they enter an incorrect password, they will most likely get a 404. If they enter the correct password, "formReturn", they are taken to the next lesson.

View the Source

Home | Contact