JavaScript prompt()/window.prompt() | Prompt Dialog Box

The JavaScript prompt() method is used to create a prompt dialog or popup box, that is obviously used to get input from user, either before entering into a page or to use the input for the current page. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="msg"></p>
   <button onclick="myFunction()">Click to Enter Name</button>
   <script>
      function myFunction() {
         let txt;
         let x = prompt("Enter Your Name: ");
         if(x==null || x=="") {
            txt = "You've not entered you name!";
         }
         else {
            txt = "Welcome " + x;
         }
         document.getElementById("msg").innerHTML = txt;
      }
   </script>
   
</body>
</html>
Output

Note - The getElementById() returns an HTML element using its ID value.

Note - The innerHTML sets/returns content to/of specified HTML element.

JavaScript prompt() Syntax

The syntax of prompt() method in JavaScript, is:

prompt("direction", "default");

The direction parameter refers to a text or message, that is used to display some direction to user, and the default parameter is used to put prior value to the input box. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="output"></p>
   <button onclick="myF()">Click to Enter the Data</button>
   <script>
      function myF() {
         let txt;
         let x = prompt("Enter Your Favourite Language: ", "JavaScript");
         if(x) {
            txt = "Wow, " + x + " is a Great Language!";
         }
         document.getElementById("output").innerHTML = txt;
      }
   </script>
   
</body>
</html>
Output

Note - The prompt() is same as window.prompt(). It is because, window is a global object. And in JavaScript, a method by default belongs to the window object.

JavaScript Online Test


« Previous Tutorial Next Tutorial »



Like/Share Us on Facebook 😋