How to Bind to Select in Svelte: Simple Guide
In Svelte, you bind to a
select element using bind:value to connect the selected option to a variable. This keeps the variable updated automatically when the user changes the selection.Syntax
Use bind:value on the <select> element to link its selected value to a variable. The variable updates when the user picks a different option.
bind:value={variable}: Connects the select's value tovariable.<option value="...">: Defines each selectable option.
svelte
<select bind:value={selected}>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="cherry">Cherry</option>
</select>Example
This example shows a select dropdown bound to a variable fruit. When you pick an option, the selected fruit name updates and displays below.
svelte
<script> let fruit = 'banana'; </script> <select bind:value={fruit} aria-label="Select a fruit"> <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="cherry">Cherry</option> </select> <p>You selected: <strong>{fruit}</strong></p>
Output
A dropdown with options Apple, Banana, Cherry. Below it shows: You selected: Banana (or the chosen fruit).
Common Pitfalls
Common mistakes when binding to select in Svelte include:
- Not using
bind:valueand trying to handleon:changemanually, which is more complex. - Forgetting to set
valueattributes onoptionelements, causing unexpected values. - Binding to a variable that is not initialized to one of the option values, which can cause no option to be selected initially.
svelte
<!-- Wrong: missing bind:value --> <select> <option value="red">Red</option> <option value="green">Green</option> </select> <!-- Right: bind:value used --> <script> let color = 'green'; </script> <select bind:value={color}> <option value="red">Red</option> <option value="green">Green</option> </select>
Quick Reference
Remember these tips when binding to select in Svelte:
- Always use
bind:valuefor two-way binding. - Set explicit
valueon eachoption. - Initialize the bound variable to a valid option value.
- Use
aria-labelorlabelfor accessibility.
Key Takeaways
Use
bind:value on select to bind the selected option to a variable.Always set
value attributes on option elements for predictable binding.Initialize the bound variable to one of the option values to show a default selection.
Avoid manual event handling for selection changes;
bind:value handles it reactively.Add accessibility labels to your
select for better user experience.