We can also use bind:value
with <select>
elements. Update line 24:
<select bind:value={selected} on:change="{() => answer = ''}">
Note that the <option>
values are objects rather than strings. Svelte doesn't mind.
Because we haven't set an initial value of
selected
, the binding will set it to the default value (the first in the list) automatically. Be careful though — until the binding is initialised,selected
remains undefined, so we can't blindly reference e.g.selected.id
in the template.
App.svelte
xxxxxxxxxx
39
1
<script>
2
let questions = [
3
{ id: 1, text: `Where did you go to school?` },
4
{ id: 2, text: `What is your mother's name?` },
5
{ id: 3, text: `What is another personal fact that an attacker could easily find with Google?` }
6
];
7
8
let selected;
9
10
let answer = '';
11
12
function handleSubmit() {
13
alert(`answered question ${selected.id} (${selected.text}) with "${answer}"`);
A11y: on:blur must be used instead of on:change, unless absolutely necessary and it causes no negative consequences for keyboard only or screen reader users. (24:1)
Console
xxxxxxxxxx
225
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
append,
5
attr,
6
destroy_each,
7
detach,
8
element,
9
init,
10
insert,
11
listen,
12
noop,
13
prevent_default,
14
run_all,
15
safe_not_equal,
16
select_option,
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
input.svelte-1sbb19g{display:block;width:500px;max-width:100%}