JavaScript Prompt Example

JavascriptFront End TechnologyObject Oriented Programming

The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus, it enables you to interact with the user. The user needs to fill in the field and then click OK. This dialog box is displayed using a method called prompt()

Following is the code for showing prompt in JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
   font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
   font-size: 18px;
   font-weight: 500;
   color: blueviolet;
}
</style>
</head>
<body>
<h1>JavaScript Prompt() method</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to get the prompt dialogue box</h3>
<script>
let resultEle = document.querySelector(".result");
document.querySelector(".Btn").addEventListener("click", () => {
   let res = prompt("Are you sure");
   if (res === null) {
      resultEle.innerHTML = "You pressed cancel";
   } else {
      resultEle.innerHTML = "You entered " + res + " in the prompt box";
   }
});
</script>
</body>
</html>

Output

On clicking on ‘CLICK HERE’ button and typing something in the promt box −

On clicking OK on the prompt box −

raja
Published on 06-May-2020 12:11:49
Advertisements