0
0
Svelteframework~5 mins

Input bindings (bind:value) in Svelte

Choose your learning style9 modes available
Introduction

Input bindings let you connect a form input directly to a variable. This means when you type, the variable updates automatically, and if the variable changes, the input shows the new value.

You want to keep a text box and a variable in sync without writing extra code.
You need to update your app immediately when a user types in a form.
You want to show a live preview of what the user is typing.
You want to simplify form handling by avoiding manual event listeners.
Syntax
Svelte
<input bind:value={variable} />
The bind:value directive connects the input's value to the variable.
Changes in the input update the variable, and changes in the variable update the input.
Examples
This example binds the input to name. Typing updates name, and the greeting updates live.
Svelte
<script>
  let name = '';
</script>

<input bind:value={name} />
<p>Hello {name}!</p>
Binding works with number inputs too. The variable age updates as you change the number.
Svelte
<script>
  let age = 30;
</script>

<input type="number" bind:value={age} />
<p>Your age is {age}</p>
For checkboxes, use bind:checked instead of bind:value.
Svelte
<script>
  let checked = false;
</script>

<input type="checkbox" bind:checked={checked} />
<p>Checked: {checked}</p>
Sample Program

This component shows a text input bound to the message variable. Whatever you type appears live below. The input has an accessible label and is styled for clarity.

Svelte
<script>
  let message = '';
</script>

<main>
  <label for="msg">Type a message:</label>
  <input id="msg" bind:value={message} placeholder="Write here..." aria-label="Message input" />
  <p>You typed: {message}</p>
</main>

<style>
  main {
    font-family: system-ui, sans-serif;
    padding: 1rem;
    max-width: 400px;
    margin: auto;
  }
  input {
    width: 100%;
    padding: 0.5rem;
    font-size: 1rem;
    margin-top: 0.5rem;
    margin-bottom: 1rem;
  }
  p {
    font-weight: bold;
  }
</style>
OutputSuccess
Important Notes

Input bindings work with text, number, textarea, and select elements.

For checkboxes and radio buttons, use bind:checked instead of bind:value.

Binding reduces the need for manual event handlers like on:input.

Summary

Input bindings connect form inputs directly to variables.

They keep the input and variable in sync automatically.

This makes handling user input simple and reactive.