Lee Stevens
Lee Stevens

Reputation: 51

How to bind the value of a select input, with dynamically created options in Svelte

I have a svelte component with a select input, that is populated with data from an external source.

How do I bind the select input so that a specific option is selected.

If I make the option values or the selected value static, it seems to work fine but not if both are dynamic.

Here is my code

<script>
    export let params = {}

    let seasons = [];
    let selected = '';

    onMount(async () => {
        selected = params.seasonId; 
    /* fetch is called here and returns a list of seasons, which is passed to seasons array */
    })
</script>

<p><select bind:value={selected}>
    <option value="" disabled>-- Select Season --</option>
    {#each seasons as season}
    <option value={season.id}>{season.description}</option>
    {/each}
</select></p>
<p>param: {params.seasonId}</p>
<p>Selected: {selected}</p>

From the code, this is the HTML output.

<p><select>
    <option value="" disabled>-- Select Season --</option>
    <option value="4">2019</option>
    <option value="3">2018</option>
    <option value="2">2017</option>
    <option value="1">2016</option>
</select></p>
<p>param: 3</p>
<p>Selected: 3</p>

I expect that once the page has loaded, option 3 "2018" would be selected but it doesn't change and "-- Select Season --" is the option selected.

Upvotes: 5

Views: 8772

Answers (3)

vitalets
vitalets

Reputation: 4973

You should additionally set selected attribute of options:

 <option value={season.id} selected={selected === season.id}>{season.description}</option>

Details here: https://github.com/sveltejs/svelte/issues/2844

Upvotes: 4

Stephane Vanraes
Stephane Vanraes

Reputation: 16411

In this simplified example of your code this seems to work: https://svelte.dev/repl/d95c63158f944ce996aaef092e4bff73?version=3.12.1

I have to note that if you change the initial selected value to

let selected = 3;

It does no longer work, so the issues is in the value of params.seasonId

Upvotes: 0

Andreas Andreou
Andreas Andreou

Reputation: 1332

This should work fine.

Without seeing more code, my guess would be that params.seasonId and season.id are of different type (the one string and the other number)

Upvotes: 0

Related Questions