Group bindings let you connect multiple inputs like checkboxes or radios to one variable easily. This helps keep your code simple and your UI in sync.
Group bindings in Svelte
<input type="checkbox" bind:group={variable} value="option1"> <input type="checkbox" bind:group={variable} value="option2"> <input type="radio" bind:group={variable} value="choice1"> <input type="radio" bind:group={variable} value="choice2">
The bind:group directive connects all inputs with the same group variable.
For checkboxes, the variable should be an array to hold multiple selected values.
For radio buttons, the variable holds a single value.
selectedFruits. When you check or uncheck, the array updates automatically.<script> let selectedFruits = []; </script> <label><input type="checkbox" bind:group={selectedFruits} value="apple"> Apple</label> <label><input type="checkbox" bind:group={selectedFruits} value="banana"> Banana</label>
selectedColor. Only one can be selected at a time.<script> let selectedColor = ''; </script> <label><input type="radio" bind:group={selectedColor} value="red"> Red</label> <label><input type="radio" bind:group={selectedColor} value="blue"> Blue</label>
This Svelte component lets users pick pizza toppings with checkboxes and size with radio buttons. The selections update the displayed order automatically.
<script> let selectedToppings = []; let selectedSize = ''; </script> <h2>Choose your pizza toppings:</h2> <label><input type="checkbox" bind:group={selectedToppings} value="cheese"> Cheese</label> <label><input type="checkbox" bind:group={selectedToppings} value="pepperoni"> Pepperoni</label> <label><input type="checkbox" bind:group={selectedToppings} value="mushrooms"> Mushrooms</label> <h2>Choose your pizza size:</h2> <label><input type="radio" bind:group={selectedSize} value="small"> Small</label> <label><input type="radio" bind:group={selectedSize} value="medium"> Medium</label> <label><input type="radio" bind:group={selectedSize} value="large"> Large</label> <h3>Your order:</h3> <p>Toppings: {selectedToppings.length > 0 ? selectedToppings.join(", ") : "None"}</p> <p>Size: {selectedSize || "Not selected"}</p>
For checkboxes, the bound variable must be an array to hold multiple values.
For radio buttons, the bound variable holds only one value at a time.
Always set the value attribute on inputs to identify each option.
Group bindings connect multiple inputs to one variable for easy state management.
Use arrays for checkbox groups and single values for radio groups.
They keep your UI and data in sync automatically with less code.