0 day streak
javascript / intermediate
Snippet

Coordinating Input Groups with bind:group

Svelte's bind:group directive simplifies handling sets of radio buttons or checkboxes. Instead of individual event listeners, it synchronizes a single variable with the value of the currently selected input in the group.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
let selectedValue = 'A';
<label>
<input type="radio" bind:group={selectedValue} value="A" />
Option A
</label>
<label>
<input type="radio" bind:group={selectedValue} value="B" />
Option B
</label>
svelte
Breakdown
1
let selectedValue = 'A';
Initializes the state variable that will hold the current selection.
2
bind:group={selectedValue}
The directive that links multiple inputs to the same reactive variable.
3
value="A"
The constant value assigned to the variable when this specific input is selected.