Once you can read what someone typed into an <input>, your page becomes something that responds. It takes one word: value.
It’s value, not textContent
When you changed text, you used textContent. Input fields work a little differently.
| What you’re reading | How you read it |
|---|---|
Text in a <p> or <h1> | textContent |
An <input> or <textarea> | value |
The contents of an input field aren’t text written in the HTML—they’re what the user just typed.
<input type="text" id="name">
<button id="greet">Say hello</button>
<p id="message"></p>const input = document.querySelector("#name");
console.log(input.value);That prints whatever is in the field. If nothing was typed, you get an empty string ("").
Read it when the button is pressed
The timing is the point: read the value at the moment of the press.
const input = document.querySelector("#name");
const message = document.querySelector("#message");
document.querySelector("#greet").addEventListener("click", function () {
message.textContent = "Hello, " + input.value + "!";
});Handling an empty field
With nothing typed, you’d greet “Hello, !”. Check first and stop when it’s empty.
const name = input.value.trim();
if (name === "") {
message.textContent = "Please type a name";
return;
}
message.textContent = "Hello, " + name + "!";.trim()— removes surrounding spaces, so input that’s only spaces counts as emptyreturn— stops here, the signal for “we can’t go further”
When you asked for a number
Everyone trips here. value hands you text, even when digits were typed.
const age = input.value; // typing 3 gives you the text "3"
console.log(age + 1); // "31"+ between two pieces of text joins them, so "3" + 1 is "31". To calculate, convert with Number().
const age = Number(input.value);
console.log(age + 1); // 4HTMLAll kinds of input fieldsChoosing the right input type, over in the HTML courseReading it from a submit button
When the button sits inside a <form>, add one line to stop the page from reloading.
document.querySelector("form").addEventListener("submit", function (event) {
event.preventDefault();
message.textContent = "Thanks, " + input.value + "!";
});event.preventDefault() is the signal that stops the form’s built-in “submit and change the page” behavior.
Summary of this lesson
- Read an input’s contents with
value(nottextContent) - Read it inside the event. Reading once outside leaves you with an empty string
- To calculate with it, convert using
Number()