javascript · level 2 · unit 2 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A 's .value holds whatever someone has typed.
An <input> tag makes a field, the box you type a name or a search into. Its .value property holds what is in it right now, always as a string, even when someone types a number.
A field fires an input event each time its words change. Listen for that and your code can react to every key: a live preview, a letter counter, a greeting that types along with you.
Need a number? Wrap the value in Number(), as you did with prompt.
<input id="nickname" placeholder="Your name">
<p id="preview">Hello, ...</p> const field = document.querySelector("#nickname");
const preview = document.querySelector("#preview");
field.addEventListener("input", () => {
preview.textContent = `Hello, ${field.value}!`;
}); Press run it to bring the page to life.
console
nothing logged yet
.value is a property, not a method, so there are no brackets after it.
guess first
Someone types 4 into the box. What does the cost say?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<input id="tickets" placeholder="How many tickets?">
<p id="cost">Cost: 0</p> const tickets = document.querySelector("#tickets");
const cost = document.querySelector("#cost");
tickets.addEventListener("input", () => {
cost.textContent = `Cost: ${tickets.value + 5}`;
});
your turn
Your turn. Count the letters.
Type the event that fires on every key in the first blank. In the second, read what is in the field. Press run and type in the box.
the page your code works on
<input id="post" placeholder="Say something short">
<p id="letters">0 letters</p>your javascript
Press run it to bring the page to life.
console
nothing logged yet
- typing Hello there shows 11 lettersnot checked yet
fix it
Typing 20 shows 2010, not 30. Fix it!
the page your code works on
<input id="price" placeholder="Price in pounds">
<p id="total">Total with postage: 10</p>your javascript
Press run it to bring the page to life.
console
nothing logged yet
- a price of 20 makes 30 in totalnot checked yet
- The listener works. Look at what kind of value
price.valueis. - A field's value is always a string, so
+joins it to 10. Turn it into a number first. - Change price.value + 10 to Number(price.value) + 10, then press run and type 20.
nailed it
your page reads what people type. :D
- A field's
.valueholds what is typed, always as a string. - The
inputevent fires each time the words change. - Wrap
.valueinNumber()before doing maths.
new words in your collection
- field
- input event
This lesson isn’t saved. A free account remembers every lesson you finish.