Javascript Window prompt() Method
The prompt()
method in JavaScript displays a dialog box that prompts the user for input. It typically provides a text field for the user to enter data.
Syntax:
prompt(message, default);
- message is a string of text to display to the user. It can be omitted if there is nothing to show in the prompt window i.e. it is optional.
- default is a string containing the default value displayed in the text input field. It is also optional.
Return value:
The prompt()
method returns the text entered by the user in the input field as a string. If the user cancels the dialog box, null
is returned.
Javascript Window prompt() Method Examples
Example: This HTML code creates an interactive webpage featuring a “Click me!” button. Upon clicking, a prompt dialog appears asking for text input. If entered, the text is displayed on the webpage with a welcoming message. Canceling the prompt does nothing.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body style="text-align: center">
<h2>Window prompt() Method</h2>
<button onclick="geek()">
Click me!
</button>
<p id="g"></p>
<script>
function geek() {
let doc = prompt(
"Please enter some text",
"GeeksforGeeks"
);
if (doc != null) {
document.getElementById(
"g"
).innerHTML =
"Welcome to " + doc;
}
}
</script>
</body>
</html>
Output:
Javascript Window prompt() Method Example Output
We have a complete list of HTML DOM methods, to check those please go through the DOM Complete Reference article.
Supported Browsers:
Last Updated :
19 Mar, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...