The select
question type lets you collect a selection from a (possibly large) number of options.
Here's a simple example:
let url = "https://raw.githubusercontent.com/ncorbuk/List-of-UK-US-Cities/master/uk-cities.txt";
let response = await form.fetch(url);
let cities = response.text.split("\n");
await form.select("What is your favorite city in England?", cities);
Which generates a question that looks like this:
A select
requires a list of choices to be passed as the second argument. This can either be an array of plain string
s, or an array of Choice
s.
A Choice
is an object that contains the label
and value
keys. The user only sees the label, but both the label and the value of the chosen answers are saved.
For example, these are both valid calls to select
:
// Plain strings
await form.select('What is your favorite color?', [
'Red', 'Green', 'Yellow', 'Blue', 'Lilac',
]);
// Choices
await form.select('What is your favorite color?', [
{label: 'Red', value: '#FF0000'},
{label: 'Green', value: '#00FF00'},
{label: 'Yellow', value: '#FFFF00'},
{label: 'Blue', value: '#0000FF'},
{label: 'Lilac', value: '#C8A2C8'},
]);
By default a select
question assumes that you only want the user to make one selection. Set the multiple
field to true
to allow multiple selection:
await form.select("What is your favorite city in England?", cities, {
multiple: true
});
select()
returns a Choice
representing the user's selection. Here's an example, assuming the user picked Red:
let colors = await form.select('What is your favorite color?', [
'Red', 'Green', 'Yellow', 'Blue', 'Lilac',
]);
form.log(colors); // {label: 'Red', value: 'Red'}
colors = await form.select('What is your favorite color?', [
{label: 'Red', value: '#FF0000'},
{label: 'Green', value: '#00FF00'},
{label: 'Yellow', value: '#FFFF00'},
]);
form.log(colors); // {label: 'Red', value: '#FF0000'}
If the multiple
option is enabled, select
returns an array of Choice
objects instead.
You can pass options to select
like so:
await form.select('What is your favorite color?', [
'Red', 'Green', 'Yellow', 'Blue', 'Lilac',
], {
single: true,
});
Here's a list of all select
-specific options:
Option | Type | |
---|---|---|
multiple |
boolean |
Allow more than one choice to be selected |
You can also pass global options, which are valid for all question types.