Part 1 / Bindings / Group inputs
If you have multiple inputs relating to the same value, you can use bind:group
along with the value
attribute. Radio inputs in the same group are mutually exclusive; checkbox inputs in the same group form an array of selected values.
Add bind:group
to each input:
<input type=radio bind:group={scoops} name="scoops" value={1}>
In this case, we could make the code simpler by moving the checkbox inputs into an each
block. First, add a menu
variable to the <script>
block...
let menu = ['Cookies and cream', 'Mint choc chip', 'Raspberry ripple'];
...then replace the second section:
<h2>Flavours</h2>
{#each menu as flavour}
<label>
<input type=checkbox bind:group={flavours} name="flavours" value={flavour}>
{flavour}
</label>
{/each}
It's now easy to expand our ice cream menu in new and exciting directions.
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
<script>
let scoops = 1;
let flavours = ['Mint choc chip'];
function join(flavours) {
if (flavours.length === 1) return flavours[0];
return `${flavours.slice(0, -1).join(', ')} and ${flavours[flavours.length - 1]}`;
}
</script>
<h2>Size</h2>
<label>
<input type=radio group={scoops} name="scoops" value={1}>
One scoop
</label>
<label>
<input type=radio group={scoops} name="scoops" value={2}>
Two scoops
</label>
<label>
<input type=radio group={scoops} name="scoops" value={3}>
Three scoops
</label>
<h2>Flavours</h2>
<label>
<input type=checkbox group={flavours} name="flavours" value="Cookies and cream">
Cookies and cream
</label>
<label>
<input type=checkbox group={flavours} name="flavours" value="Mint choc chip">
Mint choc chip
</label>
<label>
<input type=checkbox group={flavours} name="flavours" value="Raspberry ripple">
Raspberry ripple
</label>
{#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 {join(flavours)}
</p>
{/if}
initialising