How to Use bind:checked in Svelte for Checkbox Binding
In Svelte, use
bind:checked to connect a checkbox's checked state directly to a variable. This keeps the variable and checkbox in sync automatically, updating the variable when the user clicks and updating the checkbox if the variable changes.Syntax
The bind:checked directive links a checkbox input's checked state to a variable. When the checkbox is clicked, the variable updates. When the variable changes, the checkbox reflects that change.
Example parts:
<input type="checkbox": defines a checkbox input.bind:checked={variable}: binds the checkbox's checked state tovariable.
svelte
<input type="checkbox" bind:checked={variable}>
Example
This example shows a checkbox bound to a variable isChecked. Checking or unchecking the box updates the variable, and the variable's value is shown below.
svelte
<script> let isChecked = false; </script> <label> <input type="checkbox" bind:checked={isChecked}> Check me </label> <p>Checkbox is {isChecked ? 'checked' : 'unchecked'}.</p>
Output
Checkbox is unchecked.
[Checkbox shown]
When checked, text changes to: Checkbox is checked.
Common Pitfalls
Common mistakes when using bind:checked include:
- Forgetting to declare the bound variable with
let, causing errors. - Binding
checkedto a non-boolean variable, which can cause unexpected behavior. - Trying to use
bind:checkedon inputs other than checkboxes or radios.
Always ensure the variable is boolean and declared in the script.
svelte
<script> // Wrong: variable not declared // isChecked; // missing declaration causes error </script> <input type="checkbox" bind:checked={isChecked}> <!-- This will error --> <script> let isChecked = 'yes'; // Wrong: not boolean </script> <input type="checkbox" bind:checked={isChecked}> <!-- May behave unexpectedly --> <script> let isChecked = false; // Correct </script> <input type="checkbox" bind:checked={isChecked}> <!-- Correct usage -->
Quick Reference
| Feature | Description |
|---|---|
| bind:checked | Binds checkbox checked state to a boolean variable |
| Variable type | Must be boolean (true or false) |
| Input type | Only works with or |
| Two-way binding | Updates variable on user click and updates checkbox if variable changes |
| Error case | Missing variable declaration or wrong variable type causes issues |
Key Takeaways
Use bind:checked to link a checkbox's checked state to a boolean variable in Svelte.
Declare the bound variable with let and ensure it is boolean for correct behavior.
bind:checked creates two-way binding, syncing UI and variable automatically.
Only use bind:checked on checkbox or radio inputs, not other input types.
Avoid common mistakes like missing variable declaration or binding to non-boolean values.