Basic Svelte
Introduction
Bindings
Classes and styles
Advanced Svelte
Advanced reactivity
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion
We can also use bind:value
with <select>
elements:
App
<select
bind:value={selected}
onchange={() => 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.
previous next
<script>
let questions = $state([
{
id: 1,
text: `Where did you go to school?`
},
{
id: 2,
text: `What is your mother's name?`
},
{
id: 3,
text: `What is another personal fact that an attacker could easily find with Google?`
}
]);
let selected = $state();
let answer = $state('');
function handleSubmit(e) {
e.preventDefault();
alert(
`answered question ${selected.id} (${selected.text}) with "${answer}"`
);
}
</script>
<h2>Insecurity questions</h2>
<form onsubmit={handleSubmit}>
<select
value={selected}
onchange={() => (answer = '')}
>