javascript / beginner
Snippet
Synchronizing Form Inputs via Two-Way Binding Pattern in Svelte
The two-way binding pattern in Svelte utilizes the `bind:` directive to automatically synchronize JavaScript variable values with user input changes without manual event listeners.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<script>let username = '';let acceptedTerms = false;</script><form on:submit|preventDefault><label>Username:<input type="text" bind:value={username} /></label><label><input type="checkbox" bind:checked={acceptedTerms} />Accept terms and conditions</label><p>Preview: {username || 'Anonymous'} ({acceptedTerms ? 'Agreed' : 'Pending'})</p></form>
svelte
Breakdown
1
let username = '';
Defines the state variable holding the input string value.
2
<input type="text" bind:value={username} />
Binds the text field value bidirectionally to the username variable.
3
<input type="checkbox" bind:checked={acceptedTerms} />
Binds the checkbox checked state bidirectionally to the acceptedTerms boolean variable.
4
{acceptedTerms ? 'Agreed' : 'Pending'}
Evaluates the bound boolean inline with a ternary operator.