Change Input with JavaScript Summary
JavaScript can respond while someone types in an input field. This lets a webpage use the latest input value without waiting for the page to reload.
Typing in a field creates an input event. JavaScript can listen for that event, read the field’s current value, and immediately update another part of the page.
Update Content While Someone Types
First, the HTML needs an input and an element to update. Each one has an ID attribute so JavaScript can find it.
<input id="nameInput" type="text">
<p id="message">Your text will appear here.</p>
This JavaScript updates the paragraph whenever the input changes:
document.querySelector('#nameInput').addEventListener('input', () => {
document.querySelector('#message').textContent = document.querySelector('#nameInput').value;
});
When someone types Maya, the paragraph displays Maya. Each new letter changes the input value and runs the code again.
Listen for Input
The first part finds the input and listens for its input event:
document.querySelector('#nameInput').addEventListener('input', () => {
addEventListener() waits for something to happen to an element. The word input tells it to run the code whenever the text in the field changes.
The () => { begins the code that runs after each change. The closing }); finishes the instruction. This is the same pattern used for a click in the Button Click lesson, but it listens for typing instead.
Read the Current Value
The line inside the braces reads the input and changes the paragraph:
document.querySelector('#message').textContent = document.querySelector('#nameInput').value;
The value property provides the text currently inside the field. The textContent property places that text inside the paragraph. These are the same actions introduced in the Read Input and Change Text lessons.
Why Use the Input Event?
The input event lets a website respond as soon as a field changes. It can support many common interactions.
- Show a live preview of a name or message.
- Count the characters someone has typed.
- Filter a list while someone enters a search term.
- Update a total when a quantity changes.
Try Typing in the Sandbox
Select Update Code, then type inside the Name field in the preview. The paragraph will update after every change.
Change the starting paragraph text or the input placeholder and run the code again. Keep the IDs the same so the JavaScript can still find both elements.