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

Viewed 6256

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.

3 Answers

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)

Related