如果您有多个与同一个值相关的 type="radio"
或 type="checkbox"
输入,您可以使用 bind:group
以及 value
属性。同一组中的单选按钮是互斥的;同一组中的复选框会形成一个已选值的数组。
在单选按钮上添加 bind:group={scoops}
...
App
<input
type="radio"
name="scoops"
value={number}
bind:group={scoops}
/>
...在复选框上添加 bind:group={flavours}
:
App
<input
type="checkbox"
name="flavours"
value={flavour}
bind:group={flavours}
/>
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
<script>
let scoops = $state(1);
let flavours = $state([]);
const formatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
</script>
<h2>Size</h2>
{#each [1, 2, 3] as number}
<label>
<input
type="radio"
name="scoops"
value={number}
/>
{number} {number === 1 ? 'scoop' : 'scoops'}
</label>
{/each}
<h2>Flavours</h2>
{#each ['cookies and cream', 'mint choc chip', 'raspberry ripple'] as flavour}
<label>
<input
type="checkbox"
name="flavours"
value={flavour}
/>
{flavour}
</label>
{/each}
{#if flavours.length === 0}
<p>Please select at least one flavour</p>
{:else if flavours.length > scoops}
<p>Can't order more flavours than scoops!</p>
{:else}
<p>
You ordered {scoops} {scoops === 1 ? 'scoop' : 'scoops'}
of {formatter.format(flavours)}
</p>
{/if}