Prompt Box JavaScript

1. Purpose
  • Displays a dialog box with a message and an input field.
  • Allows the user to enter text input.
2. Syntax
  • Placement: JavaScript code is placed within <script> tags within the <head> or <body> of the HTML document.
let userInput = window.prompt("Enter your name:", "Default Name"); 
  • window.prompt(“Message”,”Default Value”);
    • Displays a dialog box with the specified Message.
    • The optional second argument (“Default Name”) sets the default value in the input field.
  • Returns:
    • The value entered by the user in the input field.
    • null if the user clicks “Cancel” or closes the dialog without entering any input.
3. Example:
<!DOCTYPE html>
<html>
<head>
<title>Prompt Box Example</title>
</head>
<body>
<button onclick="getUserInput()">Click Me</button>
<script>
function getUserInput() {
let name = prompt("Enter your name:", "John Doe");
if (name != null) {
alert("Hello, " + name + "!");
} else {
alert("User canceled.");
}
}
</script>
</body>
</html>
  • When the button is clicked, the getUserInput() function is called.
  • prompt(“Enter your name:”, “John Doe”); displays a dialog box asking for the user’s name with “John Doe” as the default value.
  • If the user enters a name and clicks “OK”, the alert() message displays the entered name.
  • If the user clicks “Cancel” or closes the dialog without input, the second alert() message is displayed.
Scroll to Top