JavaScript Prompt

Question: How do I display a user prompt from JavaScript?

Answer: To display a user prompt dialog, use the JavaScript prompt() method:

prompt(PromptText,SuggestedInput)

The button above was created using the following code:

<form name=myform>
<input type=button value="Try it now" 
onClick="f=prompt('Enter your name','Name');
alert('Hello '+f+'!')">
</form>

Returned Value:
If the user types something and then clicks OK or presses Enter, the prompt method returns the user input string. If the user clicks OK or presses Enter without typing anything into the prompt dialog, the method returns the suggested input as specified in the second argument passed to prompt. If the user dismisses the dialog (e.g. by clicking Cancel or pressing Esc), then in most browsers the prompt method returns null.

NOTE: Internet Explorer 7.0 and newer versions may block the JavaScript prompt dialogs for security reasons. When the prompt method is envoked, the user is presented with an information bar with the following text: This website is using a scripted window to ask you for information. If you trust this website, click here to allow scripted windows.

See also other JavaScript dialogs:

  • Alert (message box) dialog
  • Confirm dialog
  • Print dialog
  • Find dialog
  • Add Favorite dialog

    Copyright © 1999-2009, JavaScripter.net.