JavaScript Popup Boxes

Back to JS page

Table of Contents

Alert Box

An alert box is often used to display information to the user. It has an OK button.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Popup Boxes</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Alert Box</h4>
<p id="demo"></p>

<button onclick="showAlert()">Show Alert</button>

<script>
function showAlert() {
  alert("Hello! This is an alert box.");
  document.getElementById("demo").innerHTML = "Alert box was displayed!";
}
</script>

</body>
</html>

Example 1

Result View Example

Confirm Box

A confirm box asks the user to confirm something. It has OK and Cancel buttons.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Popup Boxes</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Confirm Box</h4>
<p id="demo"></p>

<button onclick="showConfirm()">Show Confirm</button>

<script>
function showConfirm() {
  let text;
  if (confirm("Do you want to continue?")) {
    text = "You clicked OK!";
  } else {
    text = "You clicked Cancel!";
  }
  document.getElementById("demo").innerHTML = text;
}
</script>

</body>
</html>

Example 2

Result View Example

Prompt Box

A prompt box asks the user to input a value. It has OK and Cancel buttons.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Popup Boxes</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Prompt Box</h4>
<p id="demo"></p>

<button onclick="showPrompt()">Show Prompt</button>

<script>
function showPrompt() {
  let person = prompt("Please enter your name:", "John Doe");
  if (person != null && person != "") {
    document.getElementById("demo").innerHTML =
      "Hello " + person + "! How are you today?";
  }
}
</script>

</body>
</html>

Example 3

Result View Example

Document

Document in project

You can Download PDF file.

Reference