prompt() asks the user for a short text value. It returns the entered string, or null when the user cancels the dialog.
const name = prompt("Please enter your name");
console.log(name);The second argument supplies an initial value in the input field.
const name = prompt("Please enter your name", "enter your first name only");The original first demo asks for a first name and displays the entered value with an alert. That behavior is preserved.
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Prompt demo</title></head>
<body>
<button id="promptButton" type="button">Click here to display Prompt Window</button>
<script>
document.getElementById("promptButton").addEventListener("click", () => {
const name = prompt("Please enter your name", "enter your first name only");
if (name !== null) {
alert(`Welcome ${name}`);
}
});
</script>
</body>
</html>The original second demo uses document.write() after the prompt. The demo remains available for historical comparison, but normal interfaces should write into an existing element instead.
DEMO of Window prompt using document.write()
function show_prompt() {
const name = prompt("Please enter your name", "enter your first name only");
document.write("Welcome " + name);
document.write('<br><br>Return to <a href="window-prompt.php">tutorial on window prompt</a>');
}document.getElementById("promptButton").addEventListener("click", () => {
const name = prompt("Please enter your name", "enter your first name only");
const output = document.getElementById("output");
output.textContent = name === null ? "Prompt cancelled" : `Welcome ${name}`;
});Because Cancel returns null, test for it before building a greeting. This avoids showing text such as “Welcome null”.
const name = prompt("Please enter your name");
if (name === null) {
console.log("The user cancelled the prompt");
} else {
console.log(`Welcome ${name}`);
}Window Object Window set interval for recursive executing Redirect Page
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.