Skip to content

Instantly share code, notes, and snippets.

@chalmagean
Last active December 22, 2016 06:21
Show Gist options
  • Save chalmagean/c0b2f874bcff728b3db047aa26b4e477 to your computer and use it in GitHub Desktop.
Save chalmagean/c0b2f874bcff728b3db047aa26b4e477 to your computer and use it in GitHub Desktop.
Elm onSelect decoder
-- Assuming we have a list of items in the model (type alias Model = { items : List Item }
-- where Item is a record like { id : Int, name : String }
-- this goes in the view and generates an html dropdown
select
[ onSelect ValueSelectedMsg ]
(List.map (\item -> option [ value (toString item.id) ] [ text item.name ]) model.items)
targetSelectedIndex : Json.Decoder Int
targetSelectedIndex =
Json.at [ "target", "selectedIndex" ] Json.int
onSelect : (Int -> msg) -> Html.Attribute msg
onSelect msg =
on "change" (Json.map msg targetSelectedIndex)
-- This will send a message containing the selected index (eg. ValueSelectedMsg 1)
@robert-hardy
Copy link

Thanks for this.
Got here from this SO answer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment