How to Use bind:group in Svelte for Radio and Checkbox Groups
In Svelte, use
bind:group to connect multiple radio buttons or checkboxes to a single variable that tracks the selected value(s). This directive automatically updates the variable when the user changes the selection, making group input handling simple and reactive.Syntax
The bind:group directive is used on input elements of type radio or checkbox. It binds the input to a shared variable that holds the selected value(s).
bind:group={variable}: Connects the input to the variable.- For
radioinputs, the variable holds the single selected value. - For
checkboxinputs, the variable is an array holding all checked values. valueattribute defines the value for each input in the group.
svelte
<input type="radio" bind:group={groupVariable} value="option1"> Option 1 <input type="radio" bind:group={groupVariable} value="option2"> Option 2
Example
This example shows a group of radio buttons bound to a variable selected. When the user picks an option, the variable updates and the selection is displayed below.
svelte
<script> let selected = 'apple'; </script> <h3>Pick a fruit:</h3> <label><input type="radio" bind:group={selected} value="apple"> Apple</label><br> <label><input type="radio" bind:group={selected} value="banana"> Banana</label><br> <label><input type="radio" bind:group={selected} value="cherry"> Cherry</label> <p>You selected: {selected}</p>
Output
Pick a fruit:
(o) Apple
( ) Banana
( ) Cherry
You selected: apple
Common Pitfalls
Common mistakes when using bind:group include:
- Not setting the
valueattribute on each input, which causes the group variable to beundefined. - Using
bind:groupon inputs of types other thanradioorcheckbox. - For checkboxes, forgetting to initialize the bound variable as an array to hold multiple selections.
svelte
<!-- Wrong: missing value attribute --> <input type="radio" bind:group={choice}> Option 1 <!-- Right: value attribute set --> <input type="radio" bind:group={choice} value="opt1"> Option 1
Quick Reference
| Feature | Description |
|---|---|
| bind:group | Binds multiple radio or checkbox inputs to one variable |
| Radio inputs | Variable holds the single selected value |
| Checkbox inputs | Variable holds an array of selected values |
| value attribute | Defines the value for each input in the group |
| Variable type | String for radio groups, array for checkbox groups |
Key Takeaways
Use bind:group to link radio or checkbox inputs to a shared variable for easy selection tracking.
Always set the value attribute on each input to define what the variable stores.
For radio buttons, the bound variable holds one value; for checkboxes, it holds an array of values.
Initialize the bound variable properly: string for radios, array for checkboxes.
Avoid using bind:group on input types other than radio or checkbox.