« home

svelte-multiselect Svelte MultiSelect

How to acquire form data in submission handler

This example shows the JavaScript way of handling MultiSelect fields in form submission events. If you’re using SvelteKit, you may want check out this example on to use form actions instead (which works even in browsers with JS disabled).

Hint: UseJSON.parse() to convert the string value passed to form submit handler back to array.

select some options, then click submit to see what data MultiSelect sends to a form submit handler
<script lang="ts">import MultiSelect from 'svelte-multiselect';
import { ColorSlot } from '$site';
import { colors } from '$site/options';
async function handle_submit(event) {
    // use bind:this={form} or event.target as arg to new FormData()
    form_data = new FormData(event.target);
}
let form_data;
// the key under which selected options are stored in FormData
const name = 'martian-flag';
</script>

<form on:submit|preventDefault={handle_submit}>
  <label for="colors">
    <strong>Which colors would you pick for the Martian flag?</strong>
  </label>
  <MultiSelect
    options={colors}
    placeholder="Pick some colors..."
    {name}
    required={2}
    let:idx
    let:option
  >
    <ColorSlot {idx} {option} />
  </MultiSelect>
  <button>Submit</button>
  <small
    >select some options, then click submit to see what data MultiSelect sends to a form
    submit handler</small
  >
</form>

{#if form_data}
  Received form data:
  <pre><code>{JSON.stringify(...form_data)}</code></pre>
  After JSON parsing<code>form_data.get(field_name)</code>:
  <pre><code>{form_data.get(name)}</code></pre>
{/if}