By the end of this lesson, learners will be able to:
<input> and <textarea> elements using JavaScriptAlmost every interactive website asks users to type something:
To make web pages truly interactive, you need to read, validate, and respond to user input using JavaScript.
<input> and <textarea>To read what a user typed, you use the .value property.
HTML:
<input type="text" id="name-input" placeholder="Enter your name" />
<textarea id="message-input" placeholder="Your message..."></textarea>
JavaScript:
let name = document.getElementById("name-input").value;
let message = document.getElementById("message-input").value;
The value is whatever the user typed in at that moment.
You usually read it inside an event handler (like when a button is clicked).
Before using input, check if it’s valid (not empty, not a number, etc.)
if (name === "") {
alert("Please enter your name.");
}
if (!isNaN(name)) {
alert("Name cannot be a number.");
}
You can also use .trim() to remove extra spaces:
if (name.trim() === "") {
alert("Name is required.");
}
Advanced validation (like regex or HTML5 constraints) is introduced in later modules.
Once the input is validated, you can use it to update other elements.
HTML:
<input type="text" id="username" placeholder="Your name" />
<button id="greet-btn">Greet</button>
<p id="greeting"></p>
JavaScript:
let input = document.getElementById("username");
let button = document.getElementById("greet-btn");
let greeting = document.getElementById("greeting");
button.addEventListener("click", function () {
let name = input.value.trim();
if (name === "") {
greeting.textContent = "Please enter your name.";
greeting.style.color = "red";
} else {
greeting.textContent = "Hello, " + name + "!";
greeting.style.color = "green";
}
});
This shows how to:
HTML:
<input type="text" id="favorite-color" placeholder="Enter your favorite color" />
<button id="show-color">Show Color</button>
<p id="color-output"></p>
Task:
JavaScript:
let input = document.getElementById("favorite-color");
let button = document.getElementById("show-color");
let output = document.getElementById("color-output");
button.addEventListener("click", function () {
let color = input.value.trim();
if (color === "") {
output.textContent = "Please enter a color.";
output.style.color = "red";
} else {
output.textContent = "Your favorite color is " + color + ".";
output.style.color = color; // Try to use it as a text color!
}
});