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

JavaScript is a potent tool for creating dynamic user experiences and adding interactivity to web pages. The prompt() function is one of the built-in JavaScript functions that accepts user input. This function gives programmers the ability to ask the user for a value or response, creating a myriad of engaging and interactive web applications. So let's start with a brief definition.

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

The prompt() function syntax in JavaScript

The syntax of the 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 the user, and the default parameter is used to put a prior value in 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() function is the same as window.prompt(). It is because window is a global object. And in JavaScript, a method by default belongs to the window object.

The following code is another example demonstrating the "prompt()" function in JavaScript:

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() function returns an HTML element using its ID value.

Note: The innerHTML sets or returns content to or from specified HTML element.

Advantages of the prompt() function in JavaScript

Disadvantages of the prompt() function in JavaScript

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!