In JavaScript popup boxes are of 3 kinds: Alert box, Confirm box and Prompt box.
Alert Box is use to give the message in a form of dialog box.
Example 1: Alert box! clicking on button alert box invoked. 1
<html> <body> <p>Click the button to display an alert box:</p> <button onclick="alertBox()">Try it</button> <script> function alertBox() { alert("Hello, I am an Alert box!"); } </script> </body> </html>
Click the button to display an alert box:
Confirm box is used when you want the user to verify or accept something.
Example 2: Confirm box! clicking on button confirm box invoked with 2 buttons, clicking on each display different message. 1
<html> <body> <p>Click the button to display a confirm box.</p> <button onclick="confirmBox()">Try it</button> <p id="confirm_message"></p> <script> function confirmBox() { var x; if (confirm("Press a button!") == true) { x = "You pressed OK!"; } else { x = "You pressed Cancel!"; } document.getElementById("confirm_message").innerHTML = x; } </script> </body> </html>
Click the button to display a confirm box.
A prompt box is often used if you want the user to input a value without occupying the space on a webpage.
Example 3: Prompt box! clicking on button prompt box invoked with a message 'Please enter your name' with a default name on clicking ok button display greet message with the name entered by user. 1
<html> <body> <p>Click the button to display a prompt box.</p> <button onclick="promptBox()">Try it</button> <p id="p1"></p> <script> function promptBox() { var x = prompt("Please enter your name", "Javascript"); if (x != null) { document.getElementById("p1").innerHTML = "Hello " + x + "! How are you?"; } } </script> </body> </html>
Click the button to display a prompt box.
Example 4: JavaScript popup boxes - alert, confirm, prompt box. 1
<html> <body> <script> function funAlert() { alert("hi , i m alert box"); } function funConfirm() { if(confirm("r u sure! You want to color bg")) { document.bgColor = "green"; } else { document.bgColor = "grey"; } } function funPrompt() { var a = prompt("Enter color name"); document.bgColor = a; document.getElementsByTagName("h1")[0].style.color = a; document.getElementsByTagName("h1")[0].style.background = "white"; } </script> </head> <body> <h1>Popup Box Example</h1> <button onclick="funAlert()">Alert</button> <button onclick="funConfirm">Confirm</button> <button onclick="funPrompt">Prompt</button> </body> </html>