Open History to see the last commit
1<script lang="ts">
2 import { createForm } from '@tanstack/svelte-form'
3β
4 const { items }: { items: Array<string> } = $props()
5 const form = createForm(() => ({
6 defaultValues: { items },
7 onSubmit: ({ value }) => {
8 console.log(value)
9 alert(`Submitted ${value.items.length} items.`)
10 },
11 }))
12</script>
13β
14<form.Subscribe selector={(state) => state.values.items.length}>
15 {#snippet children(amount)}
16 <h2>Item amount: {amount.toLocaleString()}</h2>
17 {/snippet}
18</form.Subscribe>
19<form
20 onsubmit={(event) => {
21 event.preventDefault()
22 event.stopPropagation()
23 form.handleSubmit()
24 }}
25>
26 <button type="submit">Submit</button>
27 <button
28 type="button"
29 onclick={() => form.pushFieldValue('items', 'New Field')}
30 >
31 Create item
32 </button>
33 <form.ArrayField name="items">
34 {#snippet children(array)}
35 <ul>
36 {#each array.value as _, index}
37 <form.Field name={`items[${index}]`}>
38 {#snippet children(field)}
39 <li>
40 <label>
41 <span>Field {index}</span>
42 <input
43 name={field.name}
44 value={field.value}
45 onblur={field.handleBlur}
46 oninput={(event) =>
47 field.handleChange(event.currentTarget.value)}
48 />
49 </label>
50 </li>
51 {/snippet}
52 </form.Field>
53 {/each}
54 </ul>
55 {/snippet}
56 </form.ArrayField>
57</form>