0 day streak
javascript / intermediate
Snippet

Synchronizing Radio Inputs with Group Bindings

The 'bind:group' directive allows multiple radio or checkbox inputs to share a single state variable. This ensures that only one radio button in a group is selected at a time.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
<script>
let selectedFlavor = 'Vanilla';
</script>
<label>
<input type="radio" bind:group={selectedFlavor} value="Vanilla">
Vanilla
</label>
<label>
<input type="radio" bind:group={selectedFlavor} value="Chocolate">
Chocolate
</label>
svelte
Breakdown
1
let selectedFlavor = 'Vanilla'
The reactive variable that will hold the 'value' of the currently selected input.
2
bind:group={selectedFlavor}
Connects this specific input to the shared group variable.
3
value="Vanilla"
The data that will be assigned to 'selectedFlavor' when this radio button is picked.