Select
Choose single or multiple string values with search, keyboard, form and positioning behavior. Single selections update their named value input and emit a bubbling change event. Ordinary single selects can opt into a styled native fallback before Datastar initializes; only the active control submits a value.
Basic
open System
open FSharp.ViewEngine
open Acme.Components
open type Html
open type Svg
open type Datastar
let frequencyOptions =
[ "daily", "Daily"; "weekly", "Weekly"; "monthly", "Monthly" ]
let defaultSelect =
fveField {
fveLabel {
_for "updateFrequencyDefault"
"Update frequency"
}
fveSelect {
_id "updateFrequencyDefault"
_name "updateFrequencyDefault"
_value "daily"
fveSelectContent {
for value, label in frequencyOptions do
fveSelectItem {
_value value
if value = "monthly" then
_disabled true
label
}
}
}
}This example also uses Field. See their Installation sections for any additional setup.
On this page
Installation
Copy this component and its required dependencies into the consumer-owned Components project.
dotnet fve add select --config src/Acme.Components/fve.jsonAdd to src/Acme.Web/js/app.js once, alongside your other component imports:
import '../../Acme.Components/Components/Assets/select.js';The CLI resolves dependencies and preserves consumer-authored files. See Installation for project initialization, Tailwind, the shared runtime, and building/loading your app entry.
Usage
open System
open FSharp.ViewEngine
open Acme.Components
open type Html
open type Svg
open type Datastar
let frequencyOptions =
[ "daily", "Daily"; "weekly", "Weekly"; "monthly", "Monthly" ]
let defaultSelect =
fveField {
fveLabel {
_for "updateFrequencyDefault"
"Update frequency"
}
fveSelect {
_id "updateFrequencyDefault"
_name "updateFrequencyDefault"
_value "daily"
fveSelectContent {
for value, label in frequencyOptions do
fveSelectItem {
_value value
if value = "monthly" then
_disabled true
label
}
}
}
}Compose fveSelectContent and fveSelectItem inside fveSelect or fveMultiSelect. The Select supplies its trigger and manages selection/form values; customize items with ordinary HTML.
Give remote content a stable ID and render it with the same helper for initial results and responses. The remote example includes the running handlers and routes. Items supply their own string values and labels; serialize domain values explicitly at the HTML boundary.
Custom items and groups
open System
open FSharp.ViewEngine
open Acme.Components
open type Html
open type Svg
open type Datastar
let composedStatusSelect =
let icon (name: IconName) = fveIcon { _name name; _size Size.Small }
let active = ("active", "Active", false)
let pendingChoice = ("pending", "Pending", false)
let scheduled = ("scheduled", "Scheduled", false)
fveField {
fveLabel {
_for "components-composed-status"
"Composed status"
}
fveSelect {
_value "active"
fveSelectContent {
_id "composed-status-content"
fveSelectGroup {
_label "Current"
fveSelectItem {
let value, label, disabled = active
_value value
_label label
_disabled disabled
span {
_class "flex flex-wrap items-center gap-x-2 gap-y-1 font-normal"
icon IconName.Bolt
span {
_class "whitespace-nowrap"
"Active"
}
}
}
}
fveSelectGroup {
_label "Upcoming"
fveSelectItem {
let value, label, disabled = pendingChoice
_value value
_label label
_disabled disabled
span {
_class "flex flex-wrap items-center gap-x-2 gap-y-1 font-normal"
icon IconName.Clock
span {
_class "whitespace-nowrap"
"Pending"
}
}
}
fveSelectItem {
let value, label, disabled = scheduled
_value value
_label label
_disabled disabled
span {
_class "flex flex-wrap items-center gap-x-2 gap-y-1 font-normal"
icon IconName.CalendarDays
span {
_class "whitespace-nowrap"
"Scheduled"
}
}
}
}
}
_name "composedStatus"
_id "components-composed-status"
}
}This example also uses Field, Icon. See their Installation sections for any additional setup.
Multiple selection
open System
open FSharp.ViewEngine
open Acme.Components
open type Html
open type Svg
open type Datastar
let memberOptions =
[ ("alex", "Alex Morgan", false)
("jamie", "Jamie Lee", false)
("riley", "Riley Chen", false)
("taylor", "Taylor Brooks", false)
("sam", "Sam Rivera", true) ]
let selectedMembersSelect =
fveField {
fveLabel {
_for "assignedIds"
"Assigned members"
}
fveMultiSelect {
_values ([ "alex"; "jamie"; "riley" ])
_name "assignedIds"
fveSelectContent {
for choice in memberOptions do
fveSelectItem {
let value, label, disabled = choice
_value value
_label label
_disabled disabled
}
}
_id "assignedIds"
}
}This example also uses Field. See their Installation sections for any additional setup.
Local search
open System
open FSharp.ViewEngine
open Acme.Components
open type Html
open type Svg
open type Datastar
let private searchItems =
[ "101", "Project notes"; "102", "Shared files"; "103", "Archived files" ]
let private itemOptions values =
values |> List.map (fun (value, label) -> (value, label, (value = "103")))
let staticItemCombobox =
fveField {
fveLabel {
_for "components-static-item"
"Search items"
}
fveSelect {
_search SelectSearch.Static
_value "101"
_name "staticItem"
_id "components-static-item"
fveSelectContent {
for choice in itemOptions searchItems do
fveSelectItem {
let value, label, disabled = choice
_value value
_label label
_disabled disabled
}
}
_ariaDescribedby (String.concat " " [ ("components-static-item") + "-description" ])
}
fveFieldDescription {
_id ("components-static-item" + "-description")
"Type to filter the items."
}
}This example also uses Field. See their Installation sections for any additional setup.
Remote search
open Giraffe
open Microsoft.Extensions.DependencyInjection
open StarFederation.Datastar
open StarFederation.Datastar.DependencyInjection
open System
open FSharp.ViewEngine
open Acme.Components
open type Html
open type Svg
open type Datastar
let private searchItems =
[ "101", "Project notes"; "102", "Shared files"; "103", "Archived files" ]
let private itemOptions values =
values |> List.map (fun (value, label) -> (value, label, (value = "103")))
let itemContent contentId searchText (failure: string option) (choices: (string * string * bool) list) =
fveSelectContent {
_id contentId
_query searchText
_error failure
_retry "/components/items/search?retry=true"
_emptyMessage "No matching items"
_loadingMessage "Loading items"
for choice in choices do
fveSelectItem {
let value, label, disabled = choice
_value value
_label label
_disabled disabled
}
}
let itemCombobox =
let choices = itemOptions searchItems
fveField {
fveLabel {
_for "item"
"Choose an item"
}
fveSelect {
_placeholder "Search items"
_search (SelectSearch.Remote "/components/items/search")
_name "item"
itemContent "fve-select-item-popup" "" None choices
_id "item"
_ariaDescribedby (String.concat " " [ ("item") + "-description" ])
}
fveFieldDescription {
_id ("item" + "-description")
"Search for Project notes, or type error to try the retry action."
}
}
let itemComboboxOptions contentId searchText retry =
let failed =
String.Equals(searchText, "error", StringComparison.OrdinalIgnoreCase)
&& not retry
let choices =
if failed then
[]
else
searchItems
|> List.filter (fun (_, label) ->
String.IsNullOrWhiteSpace searchText
|| label.Contains(searchText, StringComparison.OrdinalIgnoreCase))
|> itemOptions
itemContent contentId searchText (if failed then Some "Items could not be loaded." else None) choices
let selectSearchQuery signalName (context: Microsoft.AspNetCore.Http.HttpContext) =
try
use signals =
System.Text.Json.JsonDocument.Parse(context.Request.Query["datastar"].ToString())
match signals.RootElement.TryGetProperty(signalName: string) with
| true, value when value.ValueKind = System.Text.Json.JsonValueKind.String -> Some(value.GetString())
| _ -> None
with
| :? System.Text.Json.JsonException
| :? InvalidOperationException -> None
let itemSearchHandler signalName contentId : HttpHandler =
fun next context ->
task {
match selectSearchQuery signalName context with
| None ->
return! (setStatusCode 400 >=> Giraffe.Core.text "A known search field is required.") next context
| Some searchText ->
let delay =
if searchText.StartsWith("proj", StringComparison.OrdinalIgnoreCase) then
750
else
300
do! System.Threading.Tasks.Task.Delay(delay, context.RequestAborted)
let retry = context.Request.Query["retry"].ToString() = "true"
return! htmlString (itemComboboxOptions contentId searchText retry |> Render.toString) next context
}
let itemSearchRoutes: HttpHandler =
Giraffe.Core.GET
>=> route "/components/items/search"
>=> itemSearchHandler "item_query" "fve-select-item-popup"This example also uses Field. See their Installation sections for any additional setup.
Includes the running demo's Giraffe handler and routes. Mount the routes in your existing application with services.AddDatastar(); the short delay makes request loading visible.
Form validation
open System
open FSharp.ViewEngine
open Acme.Components
open type Html
open type Svg
open type Datastar
let selectStatusOptions =
[ ("active", "Active", false)
("pending", "Pending", false)
("suspended", "Suspended", true)
("scheduled", "Scheduled", false) ]
let choiceSubmitButton id (label: string) =
fveButton {
_color Color.Primary
_variant ButtonVariant.Solid
_type "submit"
_id id
label
}
let choiceResult id result =
output {
_id id
_role "status"
_class "block min-h-5 text-sm text-[var(--fve-muted-text)]"
defaultArg result "Submit the form to see the result."
}
let selectFormRegion (selection: string option) (validationMessage: string option) result =
div {
_id "components-select-form-region"
_class "grid max-w-sm gap-3"
form {
_dataOn ("submit", "@post('/components/choices/select', {contentType:'form'})")
_class "grid gap-3"
fveField {
fveLabel {
_for "components-status"
"Status"
}
fveSelect {
match selection with
| Some value -> _value value
| None -> ()
_placeholder "Choose a status"
_name "status"
_id "components-status"
_required true
fveSelectContent {
for choice in selectStatusOptions do
fveSelectItem {
let value, label, disabled = choice
_value value
_label label
_disabled disabled
}
}
_ariaInvalid (Option.isSome validationMessage)
_ariaDescribedby (
String.concat
" "
[ ("components-status") + "-description"
if Option.isSome (validationMessage) then
("components-status") + "-validation" ]
)
}
fveFieldDescription {
_id ("components-status" + "-description")
"Choose the availability of this item."
}
match validationMessage with
| Some message ->
fveFieldError {
_id ("components-status" + "-validation")
message
}
| None -> ()
}
choiceSubmitButton "components-select-submit" "Validate status"
}
choiceResult "components-select-result" result
}
let statusSelect = selectFormRegion None None NoneThis example also uses Field, Button. See their Installation sections for any additional setup.
Disabled
open System
open FSharp.ViewEngine
open Acme.Components
open type Html
open type Svg
open type Datastar
let selectStatusOptions =
[ ("active", "Active", false)
("pending", "Pending", false)
("suspended", "Suspended", true)
("scheduled", "Scheduled", false) ]
let disabledStatusSelect =
fveField {
fveLabel {
_for "components-disabled-status"
"Disabled status"
}
fveSelect {
_value "active"
_name "status"
_id "components-disabled-status"
_disabled true
fveSelectContent {
for choice in selectStatusOptions do
fveSelectItem {
let value, label, disabled = choice
_value value
_label label
_disabled disabled
}
}
}
}This example also uses Field. See their Installation sections for any additional setup.
Pending
open System
open FSharp.ViewEngine
open Acme.Components
open type Html
open type Svg
open type Datastar
let selectStatusOptions =
[ ("active", "Active", false)
("pending", "Pending", false)
("suspended", "Suspended", true)
("scheduled", "Scheduled", false) ]
let pendingStatusSelect =
fveField {
fveLabel {
_for "components-pending-status"
"Updating status"
}
fveSelect {
_value "pending"
_readonly true
_ariaBusy true
_name "status"
_id "components-pending-status"
fveSelectContent {
for choice in selectStatusOptions do
fveSelectItem {
let value, label, disabled = choice
_value value
_label label
_disabled disabled
}
}
}
}This example also uses Field. See their Installation sections for any additional setup.
API reference
type SelectSearch =
| Static
| Remote of string
type SelectPosition =
| SelectedItem
| TriggerStart
| TriggerEnd
module SelectDsl =
val fveSelect : ComponentElementBuilder
val fveMultiSelect : ComponentElementBuilder
val fveSelectContent : ComponentElementBuilder
val fveSelectItem : ComponentElementBuilder
val fveSelectGroup : ComponentElementBuilder
val fveSelectSelectedItem : ComponentElementBuilder
module SelectAttributes =
val Html._search.Static : value:SelectSearch -> HtmlAttribute
val Html._position.Static : value:SelectPosition -> HtmlAttribute
val Html._nativeFallback.Static : value:bool -> HtmlAttribute
val Html._query.Static : value:string -> HtmlAttribute
val Html._loading.Static : value:bool -> HtmlAttribute
val Html._error.Static : value:string -> HtmlAttribute
val Html._error.Static : value:string option -> HtmlAttribute
val Html._retry.Static : value:string -> HtmlAttribute
val Html._emptyMessage.Static : value:string -> HtmlAttribute
val Html._loadingMessage.Static : value:string -> HtmlAttribute