prompt() and confirm() β Browser Dialogs
prompt() shows a browser popup with a text input. It returns the string the user typed, or null if they clicked Cancel. confirm() shows a yes/no dialog and returns a boolean.
// prompt() β returns string or null
const name = prompt("What is your name?");
if (name !== null && name.trim() !== "") {
console.log(`Hello, ${name}!`);
} else {
console.log("No name provided.");
}
// prompt() with a default value (second argument)
const city = prompt("Enter your city:", "New York");
console.log("City:", city);
// confirm() β returns boolean
const agreed = confirm("Do you agree to the terms?");
if (agreed) {
console.log("User agreed!");
} else {
console.log("User declined.");
}
prompt() blocks all JavaScript execution until the user responds, creates a poor mobile experience, looks different in every browser, cannot be styled, and is disabled in some browser contexts (like iframes). Modern apps use HTML form elements with event listeners instead.
Reading DOM Input Elements
The modern way to get user input is through HTML <input> elements accessed via the DOM. The two most common methods to find an element are getElementById() and querySelector().
// HTML:
// <input type="text" id="nameInput" placeholder="Enter name">
// <button id="submitBtn">Submit</button>
// <p id="output"></p>
// Get elements
const nameInput = document.getElementById("nameInput");
const submitBtn = document.getElementById("submitBtn");
const output = document.getElementById("output");
// Same thing with querySelector (more flexible, accepts CSS selectors)
const nameInput2 = document.querySelector("#nameInput");
const firstInput = document.querySelector("input");
const allInputs = document.querySelectorAll("input"); // NodeList
// Read the input value
submitBtn.addEventListener("click", function() {
const name = nameInput.value; // always a string!
const trimmed = name.trim();
if (trimmed === "") {
output.textContent = "Please enter a name.";
} else {
output.textContent = `Hello, ${trimmed}!`;
}
});
No matter what type an input is (type="number", type="date", etc.), input.value always returns a string. Always convert explicitly: const age = Number(ageInput.value).
addEventListener β Responding to Events
Event listeners let your code respond to user actions. The most useful input events are click, input, change, and keydown/keyup.
const input = document.querySelector("#myInput");
// "input" fires on every keystroke
input.addEventListener("input", function(event) {
console.log("Current value:", event.target.value);
});
// "change" fires when element loses focus after a change
input.addEventListener("change", function(event) {
console.log("Final value:", event.target.value);
});
// "keydown" fires when any key is pressed
input.addEventListener("keydown", function(event) {
console.log("Key pressed:", event.key);
// Submit on Enter key
if (event.key === "Enter") {
console.log("Enter pressed! Submitting:", input.value);
}
});
// Click event on a button
const btn = document.querySelector("#myBtn");
btn.addEventListener("click", function() {
console.log("Button clicked!");
});
Reading Form Values
HTML forms can contain many different input types. Here's how to read each:
// <input type="text" id="name"> β use .value
const name = document.getElementById("name").value;
// <input type="number" id="age"> β use .value then convert
const age = Number(document.getElementById("age").value);
// <input type="checkbox" id="agree"> β use .checked (boolean)
const agreed = document.getElementById("agree").checked;
// <select id="color"> β use .value
const color = document.getElementById("color").value;
// <textarea id="message"> β use .value
const message = document.getElementById("message").value;
// <input type="radio" name="gender"> β find checked one
const gender = document.querySelector('input[name="gender"]:checked')?.value;
console.log({ name, age, agreed, color, message, gender });
Input Validation Basics
function validateForm() {
const name = document.getElementById("name").value.trim();
const email = document.getElementById("email").value.trim();
const age = Number(document.getElementById("age").value);
const errors = [];
if (name.length < 2) {
errors.push("Name must be at least 2 characters.");
}
if (!email.includes("@") || !email.includes(".")) {
errors.push("Please enter a valid email address.");
}
if (isNaN(age) || age < 1 || age > 120) {
errors.push("Please enter a valid age (1β120).");
}
if (errors.length > 0) {
document.getElementById("errorMsg").textContent = errors.join(" ");
return false;
}
// All valid!
document.getElementById("errorMsg").textContent = "";
return true;
}
innerHTML vs textContent for Output
When displaying results, choose between innerHTML and textContent carefully:
| Property | Parses HTML? | Security Risk? | Use When |
|---|---|---|---|
textContent | No | Safe | Displaying user-provided text |
innerHTML | Yes | XSS risk if unescaped | Inserting trusted HTML markup |
innerText | No | Safe | Similar to textContent (layout-aware) |
Setting element.innerHTML = userInput can execute malicious scripts (XSS β Cross-Site Scripting). A user could type <img src=x onerror="alert('hacked')"> as their name. Always use textContent for displaying user-provided data.
Complete Interactive Example
// HTML structure:
// <input type="text" id="nameInput" placeholder="Enter your name">
// <button id="greetBtn">Greet Me!</button>
// <p id="greeting"></p>
const nameInput = document.getElementById("nameInput");
const greetBtn = document.getElementById("greetBtn");
const greeting = document.getElementById("greeting");
function showGreeting() {
const name = nameInput.value.trim();
if (name === "") {
greeting.textContent = "Please enter your name first!";
greeting.style.color = "red";
return;
}
const hour = new Date().getHours();
let timeGreeting;
if (hour < 12) {
timeGreeting = "Good morning";
} else if (hour < 18) {
timeGreeting = "Good afternoon";
} else {
timeGreeting = "Good evening";
}
greeting.textContent = `${timeGreeting}, ${name}! Welcome to ylearner!`;
greeting.style.color = "green";
}
// Respond to button click
greetBtn.addEventListener("click", showGreeting);
// Respond to Enter key in the input
nameInput.addEventListener("keydown", function(event) {
if (event.key === "Enter") {
showGreeting();
}
});
ποΈ Practical Exercise
- Open your browser console and test
prompt("Enter a number:"). What happens if you click Cancel? - Create a simple HTML page with a text input and a button. Use
addEventListenerto log the input value when the button is clicked. - Add a
keydownlistener that triggers the same action when the user presses Enter in the input field. - Add basic validation: show an error if the input is empty or shorter than 3 characters.
- Change the output to use
textContentand confirm that HTML tags typed by the user are displayed as plain text, not rendered.
π₯ Challenge Exercise
Build a simple tip calculator. Create an HTML page with two inputs: a "Bill Amount" (number) and a "Tip Percentage" (number, default 15). Add a "Calculate" button. When clicked, validate that both fields contain valid positive numbers, then display the tip amount, total bill, and a per-person split amount (add a third input for number of people). Format all monetary outputs to 2 decimal places.
π Summary
prompt()andconfirm()show blocking browser dialogs β avoid in production.- Use
getElementById()orquerySelector()to access HTML input elements. input.valuealways returns a string β convert explicitly withNumber()when needed.addEventListener("click", fn)andaddEventListener("input", fn)are the standard way to handle user interactions.- Use
event.key === "Enter"in akeydownlistener to support keyboard submission. - Always use
textContent(notinnerHTML) to display user-provided text to prevent XSS.
Interview Questions
- What is the difference between
getElementById()andquerySelector()? - Why is it unsafe to use
innerHTMLwith user input? - What is the difference between the
inputandchangeevents? - Why should you avoid
prompt()in production applications? - How do you read the value from a checkbox vs a text input?
Frequently Asked Questions
The input event fires immediately on every keystroke or paste β it's ideal for real-time feedback like character counts or live search. The change event fires only when the element loses focus AND the value has changed since it gained focus β better for final validation or form submission triggers.
Add an event listener to the form's submit event and call event.preventDefault(): form.addEventListener("submit", function(e) { e.preventDefault(); /* your code */ }). Without preventDefault(), the form submits the traditional way (page reload or navigation to the action URL).
Simply set input.value = "". To also move focus to the field afterward, chain with input.focus(). For a complete form reset, you can call formElement.reset() to restore all fields to their default values.
Event delegation means adding one event listener to a parent element instead of multiple listeners to individual children. When a child is clicked, the event "bubbles up" to the parent. Check event.target to determine which child triggered it. This is more efficient, works for dynamically added elements, and reduces memory usage.
textContent returns all text including hidden elements and doesn't trigger a reflow. innerText is layout-aware β it only returns visible text and respects CSS styling (including display: none). For setting text output, textContent is usually preferred because it's faster and more predictable. Both are safe against XSS.