Multiple Select
Learn how to build multiple select inputs with Formsnap.
In the following guide, you'll learn how to setup and validate multiple select fields with Formsnap by building an Ice Cream order form.
Building a Multiple Select Form
Define the Schema
Here's the schema we'll use for the form we'll build in this guide. We're assuming you know how to setup the load function and actions, and have already created a +page.svelte
and +page.server.ts
file.
The schema represents an ice cream order form with a scoops
field, a flavors
field, and a toppings
field. The flavors
and toppings
fields are arrays of enums, and we've added some custom validation to ensure the user can only select as many flavors as they have scoops. We've also set a minimum of 1 for the flavors
field and a maximum of 2 for the toppings
field.
Create the Form
Let's initialize our SuperForm with the form returned from the load
function and setup the basic structure of our form. We'll also want to import the schema
, flavors
, and toppings
from the schema file.
Import the Components
At a minimum we need to import the Field, Control, Label, and FieldErrors components from Formsnap.
Create the Scoops Field
The first field we'll create is the scoops
field, which will be a regular select input with a range of 1 to 5 scoops.
Create the Flavors Field
Next, let's create the flavors
field. This field will be a multiple select input with the available flavors as options.
Notice that we're using the multiple
attribute on the select
element to allow the user to select multiple options. We're also using the selected
attribute to pre-select the options that are already in the formData.flavors
array.
Create the Toppings Field
Finally, let's create the toppings
field. This field will also be a multiple select input with the available toppings as options.
Finished Product
That's it! 🎉
You've created the functionality for a form containing multiple select inputs with validation. With some custom styles and finesse, you can make the form look something like this: