By the end of this lesson, learners will be able to:
.value
property to access input contentinput
eventUser input is the heart of interactivity on websites. Forms, search bars, chats, signups—almost everything involves letting users type and respond to what they typed.
JavaScript allows you to:
.value
Use the .value
property on input elements to get what the user typed.
<input id="name-input" type="text" placeholder="Enter your name" />
let input = document.getElementById("name-input");
let name = input.value; // returns the current text in the field
The input
event lets you respond as the user types:
<input id="live-input" placeholder="Type something..." />
<p id="display-text"></p>
let input = document.getElementById("live-input");
let display = document.getElementById("display-text");
input.addEventListener("input", function () {
display.textContent = "You typed: " + input.value;
});
This provides instant feedback, useful in live previews or search suggestions.
Before using the input, always validate it.
.trim()
to remove whitespacelet name = input.value.trim();
if (name === "") {
alert("Please enter your name.");
}
HTML:
<input id="username" type="text" placeholder="Your name" />
<button id="greet-btn">Say Hello</button>
<p id="greeting"></p>
JavaScript:
let input = document.getElementById("username");
let button = document.getElementById("greet-btn");
let output = document.getElementById("greeting");
button.addEventListener("click", function () {
let name = input.value.trim();
if (name === "") {
output.textContent = "Please enter your name.";
output.style.color = "red";
} else {
output.textContent = "Hello, " + name + "!";
output.style.color = "green";
}
});
This demonstrates:
Concept | Description |
---|---|
.value | Gets the current input from a text field |
input event | Fires as the user types |
.trim() | Removes leading/trailing whitespace |
Dynamic feedback | Update the DOM with user data |