Skip to main content
Basic Svelte
Introduction
Reactivity
Props
Logic
Events
Bindings
Classes and styles
Actions
Transitions
Advanced Svelte
Advanced reactivity
Reusing content
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
Forms
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Hooks
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion

<select> 要素にも bind:value を使用できます。

App
<select
	bind:value={selected}
	onchange={() => answer = ''}
>

<option> の値は文字列ではなくオブジェクトであることにご注意ください。Svelteは気にしません。

selected の初期値を設定していないので、バインディングは自動的にデフォルト値(配列の先頭)に設定されます。しかし、注意してください。バインディングが初期化されるまで、selected は undefined のままなので、よく考えもせずにテンプレート内の selected.id などを参照することはできません。

Edit this page on GitHub

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<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 = '')}
	>
		{#each questions as question}
			<option value={question}>
				{question.text}
			</option>
		{/each}
	</select>
 
	<input bind:value={answer} />
 
	<button disabled={!answer} type="submit">
		Submit
	</button>
</form>
 
<p>
	selected question {selected
		? selected.id
		: '[waiting...]'}
</p>