JavaScript prompt() Window for User Input

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);
On this page

Syntax and default value Top ↑

The second argument supplies an initial value in the input field.

const name = prompt("Please enter your name", "enter your first name only");

Prompt and display the result with alert() Top ↑

The original first demo asks for a first name and displays the entered value with an alert. That behavior is preserved.

DEMO of Window prompt

Complete source

<!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>

Legacy document.write() output Top ↑

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()

Original legacy pattern

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>');
}

Modern replacement

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}`;
});

Handle Cancel explicitly Top ↑

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




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer