Nếu bạn có nhiều ô type="radio" hoặc type="checkbox" mà liên quan đến cùng một giá trị, bạn có thể dùng bind:group cùng với thuộc tính value. Các ô đánh dấu (radio input) trong cùng một nhóm sẽ loại trừ lẫn nhau (chỉ được chọn một); ô lựa chọn (checkbox input) trong cùng một nhóm sẽ phân thành một mảng nhiều giá trị.
Hãy thêm bind:group={scoops} vào các ô đánh dấu...
App.svelte
<input
type="radio"
name="scoops"
value={number}
bind:group={scoops}
/>...và thêm bind:group={flavours} vào các ô lựa chọn:
App.svelte
<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
<script>
let scoops = 1;
let flavours = [];
const formatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });</script>
<h2>Kích cỡ</h2>
{#each [1, 2, 3] as number}<label>
<input
type="radio"
name="scoops"
value={number}/>
{number} muỗng</label>
{/each}<h2>Hương vị</h2>
{#each ['bánh quy và kem', 'socola bạc hà', 'ngũ quả mâm xôi'] as flavour}<label>
<input
type="checkbox"
name="flavours"
value={flavour}/>
{flavour}</label>
{/each}{#if flavours.length === 0}<p>Hãy chọn một hoặc nhiều hương vị</p>
{:else if flavours.length > scoops}<p>Không thể đặt hương vị nhiều hơn muỗng kem!</p>
{:else}<p>
Bạn đã đặt {scoops} muỗng {formatter.format(flavours)}</p>
{/if}