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


or just, in the current window:



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)">

Confirm: Ask whether or not

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

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


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)">

Practical example of use of the answer:

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

Prompt: Enter a message

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


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))">

Example of use of the text typed by the user:

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