0
0
SvelteHow-ToBeginner · 3 min read

How to Use bind:value in Svelte for Two-Way Binding

In Svelte, use bind:value to connect an input element's value directly to a variable, enabling two-way binding. This means when the input changes, the variable updates automatically, and when the variable changes, the input reflects the new value.
📐

Syntax

The bind:value directive links an input's value to a variable. It uses the pattern <input bind:value={variable} />. Here, variable is a JavaScript variable declared in your Svelte component.

  • bind:value: Directive to bind the input's value.
  • {variable}: The variable that stores the input's current value.
svelte
<script>
  let name = '';
</script>

<input bind:value={name} placeholder="Enter your name" />
<p>Your name is: {name}</p>
Output
An input box with placeholder 'Enter your name' and below it text that updates live showing 'Your name is: ' followed by what you type.
💻

Example

This example shows how bind:value keeps the input and variable in sync. Typing in the input updates the variable, and changing the variable updates the input.

svelte
<script>
  let message = 'Hello';
</script>

<input bind:value={message} />
<p>Message: {message}</p>

<button on:click={() => message = 'Hi there!'}>Change Message</button>
Output
An input box showing 'Hello' initially, a paragraph showing 'Message: Hello', and a button. Typing changes the message text live. Clicking the button changes input and paragraph to 'Hi there!'.
⚠️

Common Pitfalls

Common mistakes when using bind:value include:

  • Not declaring the variable before binding it.
  • Trying to bind value on elements that don't support it (like div).
  • Using bind:value with read-only inputs or disabled fields where changes can't happen.
  • Forgetting that bind:value creates two-way binding, so changing the variable updates the input too.
svelte
<script>
  // Wrong: variable not declared
  // <input bind:value={text} />

  // Right:
  let text = '';
</script>

<input bind:value={text} />
Output
An input box that updates the variable 'text' as you type.
📊

Quick Reference

FeatureDescription
bind:valueBinds input's value to a variable for two-way data binding.
VariableA JavaScript variable declared in the