Skip to content

JavaScript Popup Boxes

  • by

JavaScript has three kinds of popup boxes: Alert box, Confirm box, and Prompt box.

window.alert("sometext");

window.confirm("sometext");

window.prompt("sometext","defaultText");

The popup boxes are used to notify, warn, or get input from the user. It also prevents the user from accessing other aspects of a program until the popup is closed, so they should not be overused.

JavaScript Popup Boxes

A Simple example code and an alert dialog box to inform or alert the user by displaying some messages in a small dialogue box. When the alert box is displayed to the user, the user needs to press ok and proceed.

<!DOCTYPE html>
<html>
<body>

  <script>
    function showAlert() {
      alert("Hi, this is an Alert box");
    }
  </script>
  <button onclick="showAlert()">Show Alert</button>

</body>
</html>

A confirmation box is used to let the user make a choice. When a confirm box pops up, the user will have to click either “OK” or “Cancel” to proceed. If the user clicks “OK”, the box returns true. If the user clicks “Cancel”, the box returns false.

<!DOCTYPE html>
<html>
<body>

  <button onclick="myFunction()">Open</button>

  <script>
    function myFunction() {
      var txt;
      if (confirm("Press a button!")) {
        txt = "You pressed OK!";
      } else {
        txt = "You pressed Cancel!";
      }
      console.log(txt);
    }
  </script>

</body>
</html>

The prompt box which is used to get the user input for further use. When a prompt box pops up, the user will have to click either “OK” or “Cancel” to proceed after entering an input value.

If the user clicks “OK” the box returns the input value. If the user clicks “Cancel” the box returns null.

<html>  
<head>  
  <script>  
    function fun() {  
      prompt ("This is a prompt box", "Hello world");  
    }  
  </script>  
</head>  

<body>  
  <p> Click the following button to see the effect </p>  
  <form>  
    <input type = "button" value = "Click me" onclick = "fun();" />  
  </form>  
</body>  
</html>  

Outputs:

Confirmation box

Do comment if you have any doubts or suggestions on this Js box topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading