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 −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
body {
   font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
.result {
   font-size: 18px;
   font-weight: 500;
   color: blueviolet;
<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>
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";


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

On clicking OK on the prompt box −

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