How to Listen for Input Changes
A simple guide on how to use the input event in TypeScript to react when a user types into a text field.
When you have a search box or any text field, you often want to do something as
the user types. The input event is the best way to do this because it fires
immediately whenever the text changes.
Here is a search input inside a dialog. We want to log the current text to the console as the user types.
HTML
<dialog id="search-box-container">
<section id="search-box">
<header>
<input id="search-input" type="text" placeholder="Search" />
</header>
</section>
</dialog>You can add an input event listener directly to the text field.
TypeScript
document.addEventListener("DOMContentLoaded", () => {
const searchInput =
document.querySelector<HTMLInputElement>("#search-input");
if (searchInput) {
const handleInput = (event: Event) => {
const target = event.target as HTMLInputElement;
const query = target.value;
console.log("Current value:", query);
// You can do something with the query here
if (query.length > 2) {
console.log(`Query is long enough to search for: ${query}`);
}
};
searchInput.addEventListener("input", handleInput);
}
});How it works:
searchInput.addEventListener("input", ...): Theinputevent fires every time the value of the<input>changes. This is the most reliable way to track user input, as it covers typing, pasting, cutting, and other ways of changing the text.handleInput(event: Event): This is our handler function.- The
event.targetis the element that fired the event, which is our<input>. - We tell TypeScript that the target is an
HTMLInputElementusingas. This is so we can safely access itsvalueproperty. target.valuegives us the current text inside the input field.
- The