Consider this Svelte component with a select bound to selected. What will be the value of selected after choosing the option labeled "Two"?
<script>
let selected = '1';
</script>
<select bind:value={selected}>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>Remember that HTML option values are always strings unless converted.
The value attribute of an option is always a string. Binding selected to value means selected will be a string matching the chosen option's value.
Given this Svelte code with a multiple select, what will be the value of selected after the user selects "Apple" and "Cherry"?
<script>
let selected = [];
</script>
<select bind:value={selected} multiple>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="cherry">Cherry</option>
</select>Multiple select bindings use arrays of strings matching option values.
When multiple is set, the bound variable is an array of strings representing the selected option values.
You want to bind a select's value to a number variable count. Which code snippet correctly achieves this in Svelte?
Binding to a number requires option values to be numbers, not strings.
Using value={1} sets the option value as a number. Binding count to value keeps it a number. Using strings will keep count as a string.
Given this Svelte code, why does selected remain empty after selecting options?
<script>
let selected = [];
</script>
<select bind:value={selected}>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>Multiple selections require a special attribute on the select element.
Without the multiple attribute, the select only allows one choice and binding expects a string, not an array. So the array selected does not update.
In Svelte, if you bind a select to a variable and use option elements with value set to objects, what happens when you select an option?
<script>
let selected;
const options = [
{ id: 1, name: 'One' },
{ id: 2, name: 'Two' }
];
</script>
<select bind:value={selected}>
{#each options as option}
<option value={option}>{option.name}</option>
{/each}
</select>Svelte supports binding non-primitive values like objects in select options using strict equality.
Unlike plain HTML, Svelte stores the original JS value (the object reference) in a private property on the option BOM element and uses === to determine which option is selected and to update the bound variable accordingly. This allows seamless binding of objects, numbers, dates, etc.