0
0
SvelteHow-ToBeginner · 3 min read

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 radio inputs, the variable holds the single selected value.
  • For checkbox inputs, the variable is an array holding all checked values.
  • value attribute 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 value attribute on each input, which causes the group variable to be undefined.
  • Using bind:group on inputs of types other than radio or checkbox.
  • 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

FeatureDescription
bind:groupBinds multiple radio or checkbox inputs to one variable
Radio inputsVariable holds the single selected value
Checkbox inputsVariable holds an array of selected values
value attributeDefines the value for each input in the group
Variable typeString 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.