How to Use on:input in Svelte for Input Event Handling
In Svelte, use
on:input to listen for input events on form elements like <input> or <textarea>. Attach it directly to the element with a function or inline code to react whenever the user types or changes the input value.Syntax
The on:input directive attaches an event listener for the input event on an element. It triggers every time the user changes the input's value.
Example parts:
on:input: the event directive{handler}: a function or inline code to run on input- Used on input elements like
<input>,<textarea>, or<select>
svelte
<input on:input={handleInput} placeholder="Type here" />Example
This example shows how to update a variable as the user types in an input box using on:input. The displayed text updates live.
svelte
<script> let name = ''; function handleInput(event) { name = event.target.value; } </script> <input on:input={handleInput} placeholder="Enter your name" /> <p>Hello, {name}!</p>
Output
An input box with placeholder 'Enter your name' and below it text that updates live to 'Hello, [typed name]!' as you type.
Common Pitfalls
Common mistakes when using on:input include:
- Not accessing
event.target.valueto get the input's current value. - Using
on:changeinstead, which only fires when the input loses focus. - Trying to update variables without reactivity, so UI does not update.
Always use event.target.value inside the handler to get the latest input.
svelte
<!-- Wrong: does not update variable --> <script> let text = ''; function wrongHandler() { text = 'fixed'; // ignores input value } </script> <input on:input={wrongHandler} /> <p>{text}</p> <!-- Right: updates with input value --> <script> let text = ''; function rightHandler(event) { text = event.target.value; } </script> <input on:input={rightHandler} /> <p>{text}</p>
Output
Two input boxes: the first does not update the text below as you type, the second updates the text live with what you type.
Quick Reference
| Directive | Description | Typical Use |
|---|---|---|
| on:input | Listens for input changes as user types | Live input value updates |
| on:change | Fires when input loses focus after change | Final input value confirmation |
| bind:value | Two-way binding of input value to variable | Simplifies input handling |
Key Takeaways
Use
on:input to react immediately as the user types in input fields.Access the current input value with
event.target.value inside the handler.Avoid confusing
on:input with on:change, which fires less frequently.For simpler code, consider using
bind:value for two-way binding instead of manual handlers.Always ensure your handler updates reactive variables so the UI updates automatically.