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} 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} value={flavour}>
{flavour}
</label>
{/each}
It's now easy to expand our ice cream menu in new and exciting directions.
App.svelte
xxxxxxxxxx
55
1
<script>
2
let scoops = 1;
3
let flavours = ['Mint choc chip'];
4
5
function join(flavours) {
6
if (flavours.length === 1) return flavours[0];
7
return `${flavours.slice(0, -1).join(', ')} and ${flavours[flavours.length - 1]}`;
8
}
9
</script>
10
11
<h2>Size</h2>
12
13
<label>
14
<input type=radio group={scoops} value={1}>
15
One scoop
16
</label>
17
18
<label>
19
<input type=radio group={scoops} value={2}>
Console
xxxxxxxxxx
251
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
append,
5
attr,
6
detach,
7
element,
8
empty,
9
init,
10
insert,
11
noop,
12
safe_not_equal,
13
space,
14
text
15
} from "svelte/internal";
16
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
/* Add a <style> tag to see compiled CSS */