Skip to content

Prompt box in JavaScript

  • by

You can use the prompt() method to display a prompt box that prompts the user for the input in JavaScript. When the prompt box pops up, we must click “OK” or “Cancel” to proceed.

prompt(text, defaultText)

The first argument is the label which displays in the text box, and the second argument is the default string, which displays in the textbox.

If the user clicks “OK,” the box returns the input value. Otherwise, it returns null on clicking “Cancel”.

Note: A prompt box is used if you want the user to input a value.

Prompt box in JavaScript

Simple example code.

<html>  
<head>  
  <script>  
    function fun() {  
      prompt ("This is a prompt box", "Hello world");  
    }  
  </script>  
</head>  

<body>  
  <p> Click the following button to see the effect </p>  
  <form>  
    <input type = "button" value = "Click me" onclick = "fun();" />  
  </form>  
</body>  
</html>  

Output:

Prompt box in JavaScript

Another example

Prompt for a user name and output a message:

<!DOCTYPE html>
<html>
<body>

  <button onclick="myFunction()">Try it</button>

  <script>
    function myFunction() {
      let person = prompt("Please enter your name", "Harry Potter");
      if (person != null) {
        console.log("Hello " + person + "! How are you today?")
      }
    }
  </script>

</body>
</html>

Output: Hello Harry Potter! How are you today?

Difference between an alert box and prompt box in JavaScript

An alert box is one type of popup box in JavaScript which is often used to make sure that information has come through the user. So, the user will have to click “OK” to proceed when an alert box pops up on the window.

Prompt boxes in JavaScript which is often taking input a value before entering a page from the user. To proceed after entering an input value in the prompt, the user will have to click either “OK” or “Cancel”.

Do comment if you have any doubts or suggestions on this Js topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading