Svelte: Select fields

bind:value also works for the select form field to get the selected value automatically assigned to the value of a variable:

<script>
let selected
</script>

<select bind:value={selected}>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

{selected}

The cool thing is that if you generate options dynamically from an array of objects, the selected option is now an object, not a string:

<script>
let selected

const goodDogs = [
  { name: 'Roger' },
  { name: 'Syd' }
]
</script>

<h2>List of possible good dogs:</h2>
<select bind:value={selected}>
  {#each goodDogs as goodDog}
    <option value={goodDog}>{goodDog.name}</option>
  {/each}
</select>

{#if selected}
<h2>
  Good dog selected: {selected.name}
</h2>
{/if}

See example: https://svelte.dev/repl/7e06f9b7becd4c57880db5ed184ea0f3

select also allows the multiple attribute:

Leave a comment

Your email address will not be published. Required fields are marked *