Intro. to JavaScript Prompt:

A prompt asks for input from the audience using a pop-up dialogue box or window that requires the audience's response before proceeding to, or displaying, the page.

The audience's response may be to type something and click OK, just to click OK, or to hit Cancel. Doing of the above is required before the page will fully load/display.

Whatever the audience types in or clicks to respond, the response is held in a variable to be used later (to be compared in an if statement, concatenated, etc.)


Basic Syntax:

Declare a local variable, and set it to hold what the script gets back from the prompt:

var theansweris42 = prompt("What is the meaning of life?");

theansweris42 is the variable, and it will hold whatever the user types in or clicks as a result of the prompt() command.

If the audience types something in to the prompt, whether or not it is words or numbers, the variable holding the prompt result will receive a string. Prompts always return user-typed information as a string, even if the user typed in a number.

If the audience doesn't type anything and just clicks OK, the string will be empty, or "".

If the audience hits Cancel, the variable the variable holding the prompt result will receive the result: null

My experience lately suggests that Safari does not always process a null correctly, and may return a "" instead.


Example in a page:

Because using just the basic syntax above isn't very useful for anything because it only allows the user to type, but doesn't do anything with what they type, we could add a conditional statement (an if statement) to add additional functionality.

This script goes inside the head tags (notice this particular example does not use a function):

<script>

var theansweris42 = prompt("What is the meaning of life?");

var reply2answer = "";

if (theansweris42 == "42") {
  	reply2answer = "So you know Douglas Adams!";
  }
else if (theansweris42 == "Love" || theansweris42 == "love") {
		/* strings are case sensitive */
  	reply2answer = "So you affirm the importance of love!";
  }
else if (theansweris42 == "") {
  	reply2answer = "You can't just hit OK to the meaning of life!";
  }
else if (theansweris42 == null) {
  	reply2answer = "You can't cancel the meaning of life!";
  }
else {
  	alert("The meaning of life is " + theansweris42 + " ?");
  	reply2answer = "This surprises me a little...";
  }
	
alert(reply2answer);

</script>

See this example in action: prompttest.html


Basic Syntax - With Suggestion Already in the Text Area:

The prompt command can also contain 2 strings. The second string will show up in the text area where the user types (as a suggestion or kind of default answer):
var usernoun = prompt("Enter a noun:", "porcupine");

So the above example would put the string "porcupine" into the area where the user types...