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 file name (less file extension) to access a page. The file name is assigned to the location.href string, which will load that page. For simplicity's sake, there is no error checking against actual pages on this site. Test the example script for an empty string.
function checkPage(){

var pageName = prompt("Enter the file name of any page on this site", "")

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

   location.href = pageName + ".html"

   }

   else {

   alert("You must enter the actual page name in order to go to that lesson.")

   }

}
function checkPage()

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.

 


Home | Contact