JavaScript prompt() method is used to display a dialog box that prompts the user to input of user data. It waits until the user enters any value in the text box or we can also cancel the dialog box.
prompt(message, default)
message: It is an optional parameter. It is the text displays to the user.
default: It is also an optional parameter. The default input text.
JavaScript prompt() method example
Simple HTML example code using prompt()
method to ask the user for their name and then display a greeting message:
<!DOCTYPE html>
<html>
<body>
<script>
let name = prompt("Type your name:");
if (name != null) {
alert("Hello, " + name + "!");
} else {
alert("You did not enter a name.");
}
</script>
</body>
</html>
Output:
Another example prompt box with a message and two buttons (OK and Cancel).
<!DOCTYPE html>
<html>
<body>
<script>
function fun() {
prompt ("This is a prompt box", "Hello world");
}
</script>
<p> Click the following button to see the effect </p>
<form>
<input type = "button" value = "Click me" onclick = "fun();" />
</form>
</body>
</html>
Do comment if you have any doubts or suggestions on this JS prompt dialog box topic
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version