Dialog box or alert message in JavaScript

Dialog boxes are methods of the window object. However, we can invoke them without explicit reference to window. They may be used depending on the type (alert, confirm, prompt) to display an information or to get input from the user.

Alert: Display a message

window.alert("Hello");

or just, in the current window:

alert("Hello");

Demonstration

Code of the demonstration:

<form name="form1" >
    <input name="alert1" type="text" value="Hello">
     <input type="button" value="Send" onclick="alert(document.form1.alert1.value)">
</form>

Confirm: Ask whether or not

var answer = window.confirm("Oui ou non?"); 

A boolean value is returned, true for yes, false for no.

Demonstration

Code of the demonstration:

<form name="form2" >
    <input name="confirm2" type="text" value="Yes or no?">
     <input type="button"  value="Send" onclick="confirm(document.form2.confirm1.value)">
</form>

Practical example of use of the answer:

var answer = window.confirm("Your choice?");
if(answer)
{ alert("Yes"); } else { alert("No"); }

Prompt: Enter a message

var answer = window.prompt("Your answer?", "Initial value..."); 

Demonstration

The initial default value is optional. This method returns the string that the user has entered or the default value if the user clicks OK without typing anything.
If the user clicks Cancel, the method returns null.

Code of the demonstration:

<form name="form3" >
    <input name="prompt3" type="text" value="Your answer?">
    <input name="prompt4" type="text" value="Initial value...">
     <input type="button"  value="Send" onclick="alert(prompt(
          document.form3.prompt3.value, document.form3.prompt4.value))">
</form>

Example of use of the text typed by the user:

var answer = window.prompt("Your answer?", "Maybe...");
if(answer)
{ alert(answer); }
© 2009-2012 Xul.fr