JavaScript prompts (input boxes)

A prompt (or input box) is a popup box which asks the user a question and allows them to type and submit their answer in a textbox. The user must enter a value in the textbox or click on OK/cancel before they can continue interacting with the webpage.

These prompts can be intrusive and annoying so only use them when absolutely necessary. Forms are a better way of getting user input. The only data validation being used in this example is checking whether the input text box is empty or not.

Watch the video below and then scroll down to see the sample code.

Here is the code for the prompt box:

<!DOCTYPE html>
<html lang="en">
 <meta charset="utf-8"/>
 <title>JavaScript Prompt Box</title>
 <script type="text/javascript">
 // This is a prompt box which asks for a name
 // The name is then displayed in the browser (only if a name is entered)
 var name=prompt("Please enter your name","Enter name here");
 if (name!=null) // this means if the name is NOT empty
 message="Hello " + name + "! How are you today?";

Here are some questions to consider after using the sample code:

  • What happens when the user clicks on OK before replacing the default value with their own text value? Can this be changed?
  • What will be displayed in the message if the user clicks on Cancel? How can this be changed?
  • Can you think of a better way of asking the user a question and using their input, rather than using a JavaScript prompt?

Next tutorial: Using the HTML5 canvas tag to draw shapes