0
0
Svelteframework~5 mins

Select bindings in Svelte

Choose your learning style9 modes available
Introduction

Select bindings let you connect a dropdown menu directly to a variable. This means when you pick an option, the variable updates automatically.

You want to let users pick one choice from a list, like selecting a country.
You need to show a dropdown that changes a setting in your app instantly.
You want to keep your code simple by linking the dropdown to a variable without extra code.
Syntax
Svelte
<select bind:value={variable}>
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
</select>
Use bind:value to connect the select's chosen value to a variable.
The variable updates automatically when the user picks a different option.
Examples
This example shows a dropdown for fruits. The selected fruit is shown below and updates as you pick different options.
Svelte
<script>
  let fruit = 'apple';
</script>

<select bind:value={fruit}>
  <option value="apple">Apple</option>
  <option value="banana">Banana</option>
  <option value="orange">Orange</option>
</select>

<p>You selected: {fruit}</p>
This example adds an ARIA label for accessibility, helping screen readers describe the dropdown.
Svelte
<script>
  let color = 'red';
</script>

<select bind:value={color} aria-label="Choose a color">
  <option value="red">Red</option>
  <option value="green">Green</option>
  <option value="blue">Blue</option>
</select>

<p>Selected color: {color}</p>
Sample Program

This complete Svelte component shows a labeled dropdown to pick a city. The chosen city updates below automatically. The label and ARIA attribute improve accessibility.

Svelte
<script>
  let city = 'newyork';
</script>

<label for="city-select">Choose a city:</label>
<select id="city-select" bind:value={city} aria-label="City selection">
  <option value="newyork">New York</option>
  <option value="london">London</option>
  <option value="tokyo">Tokyo</option>
</select>

<p>Your chosen city is: {city}</p>
OutputSuccess
Important Notes

Always use a <label> with for matching the id of the <select> for better accessibility.

Use aria-label if you don't have a visible label to help screen readers.

The bound variable updates instantly when the user changes the selection, no extra event handling needed.

Summary

Select bindings connect dropdown menus directly to variables.

They keep your code simple and reactive.

Always add labels or ARIA attributes for accessibility.